Accessing HTTP Error Response Body from HttpInterceptor in Angular

前端 未结 2 2026
难免孤独
难免孤独 2020-12-30 05:11

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 hold

相关标签:
2条回答
  • 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:

    • Insider’s guide into interceptors and HttpClient mechanics in Angular
    0 讨论(0)
  • 2020-12-30 05:36

    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

    0 讨论(0)
提交回复
热议问题