Как я могу поймать коды ошибок HTTP, используя HttpErrorResponse в Angular 2? - PullRequest
0 голосов
/ 06 июля 2019

Я использую httpClient для отправки почтовых запросов и перехвата ошибок с помощью Interceptor. Проблема в том, что я не могу получить код состояния 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);
      })
    );
  }
}
...