Search code examples
angularrxjsangular-httpclientangular-http-interceptors

How to access error response body inside of an interceptor?


I use interceptor to sniff all HTTP requests/responses.

How to get body response in case when server returns http 400, Angular raises an exception and in catch block I can not get body message:

return next.handle(request).pipe(
   catchError((error: HttpErrorResponse) => {
          console.log(error.body); // There is not body object here
});

Solution

  • Here is an example how you can do it with help of Interceptor

      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
          catchError(error => this.handleError(error))
        );
      }
    
      private handleError(error: HttpErrorResponse): Observable<any> {
         if (error.status === 400) {
          // Do your thing here      
       }         
      }
    

    I hope it helps you out.