Accessing HTTP Error Response Body from HttpInterceptor in Angular
Asked Answered
R

2

19

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);
      }
    });
  }
}
Rosalindrosalinda answered 20/10, 2017 at 13:3 Comment(0)
D
26

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:

Diplex answered 20/10, 2017 at 14:11 Comment(7)
Thanks! It indeed works now. I was on version 4.3.6 actually (also updated in my original question) and there the error was null. But now on version 4.4.6 everything works fine.Rosalindrosalinda
I was about to capture the error messages, I am pursuing how to extract the success messages when the API request has been completed successfully say status code 200/201 etc. How can I pass the http response from return next.handle(req).do(event=> {console.log(event);//gives whole http response}) how can I return this repsonse to my component from where I am making request. I am using ngrx 4Dulaney
This is no longer the case in Angular6, error.error returns a Blob, not the actual body string...Entranceway
@reven, thanks for the info, it means they fixed it.Diplex
@MaxKoretskyiakaWizard so how to get the body from HttpErrorResponse when error.error is returning a blob ?Uel
@NitishKumar, I'm not sure what you mean. Can you please ask another question with more details?Diplex
@MaxKoretskyiakaWizard Here is what I wanted to ask #53758780Uel
S
7

To make full use of Typescript I usually create an interface that extends HttpErrorResponse:

interface APIErrorResponse extends HttpErrorResponse {
   error: {
      id?: string
      links?: { about: string }
      status: string
      code?: string
      title: string
      detail: string
      source?: {
         pointer?: string
         parameter?: string
      }
      meta?: any
      }
}

After that, just assign APIErrorResponse instead of HttpErrorResponse to your error object and access your server's custom error as mentioned above: error.error

Satiated answered 24/7, 2018 at 16:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.