Search code examples
angulartypescripthttp-errorangular-http-interceptors

Accessing HTTP Error Response Body from HttpInterceptor in Angular


I have an HttpInterceptor to catch errors and display them in a modal. Besides error code and message, I would also like to show the body of the response which actually holds a more precise description of the error (e.g. on a 500 internal server error). How can I achieve this in angular? (I am using version 4.3.6.)

I already looked at related questions but answers like HttpErrorResponse._body or similar don't work for me. Also, when inspecting the error response in the console, HttpErrorResponse.error is set to null.

Here is how my interceptor currently looks:

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  public constructor(private httpErrorService: HttpErrorService) { }

  public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).do(event => {
    }, (error: HttpErrorResponse) => {
      console.log('HTTPERROR INTERCEPTOR');
      console.log(error);
      if (error.status >= 400) {
        this.httpErrorService.onError(error);
      }
    });
  }
}

Solution

  • The answer applies to versions of Angular below 6.

    The body should be available in the error property, so:

    return next.handle(req).do(event => {
    }, (error: HttpErrorResponse) => {
      console.log(error.error); // body
      ...
    });
    

    Here is the gist of the implementation from the sources:

    if (ok) {
      ...
    } else {
      // An unsuccessful request is delivered on the error channel.
      observer.error(new HttpErrorResponse({
        // The error in this case is the response body (error from the server).
        error: body,   <--------------------
        headers,
        status,
        statusText,
        url: url || undefined,
      }));
    }
    

    To learn more about mechanics behind interceptors read: