在 Angular 中从 HttpInterceptor 访问 HTTP 错误响应正文

Accessing HTTP Error Response Body from HttpInterceptor in Angular

我有一个 HttpInterceptor 来捕获错误并在模式中显示它们。除了错误代码和消息,我还想显示响应的主体,它实际上包含对错误的更精确描述(例如,在 500 内部服务器错误上)。 我怎样才能在 angular 中做到这一点? (我使用的是 4.3.6 版本。)

我已经查看了相关问题,但 HttpErrorResponse._body 或类似的答案对我不起作用。 此外,在控制台中检查错误响应时,HttpErrorResponse.error 设置为 null。

这是我的拦截器当前的样子:

@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);
      }
    });
  }
}

答案适用于 Angular 6 以下的版本。

正文应该在 error 属性 中可用,所以:

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

这里是实现的要点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,
  }));
}

要了解有关拦截器背后机制的更多信息,请阅读:

为了充分利用 Typescript,我通常会创建一个扩展 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
      }
}

之后,只需将 APIErrorResponse 而不是 HttpErrorResponse 分配给您的错误对象并访问您服务器的自定义错误,如上所述:error.error