如何在Angular 2中使用HttpErrorResponse捕获HTTP错误代码?

时间:2019-07-06 04:47:11

标签: javascript angular7 angular2-services http-response-codes

我正在使用httpClient发送拦截请求并发送帖子请求并捕获错误。问题是我无法获取HTTP状态代码。 HttpErrorResponse的状态始终为零。

status: 0
statusText: "Unknown Error"

但是浏览器中出现404错误: enter image description here

这是我的拦截器类:

export class HttpErrorInterceptor implements HttpInterceptor {
  constructor(public toastr: ToastrService) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      retry(3),
      catchError((error: HttpErrorResponse) => {
        let errorMessage = '';
        if (error.error instanceof ErrorEvent) {
          // client-side error
          errorMessage = `Error: ${error.error.message}`;

        } else if (error.error instanceof HttpErrorResponse) {
          // server-side error
          errorMessage = 'Http error with code: ' + error.status;
        }

        console.log(error);

        // Display the error
        this.toastr.error(errorMessage);
        return throwError(error);
      })
    );
  }
}

0 个答案:

没有答案