【问题标题】:Accessing HTTP Error Response Body from HttpInterceptor in Angular从 Angular 中的 HttpInterceptor 访问 HTTP 错误响应正文
【发布时间】:2018-04-01 15:50:22
【问题描述】:

我有一个 HttpInterceptor 来捕获错误并以模式显示它们。除了错误代码和消息之外,我还想显示响应的正文,它实际上包含对错误的更精确描述(例如,关于 500 内部服务器错误)。 我怎样才能在角度上实现这一点? (我使用的是 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 typescript http-error angular-http-interceptors


    【解决方案1】:

    答案适用于 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,
      }));
    }
    

    要详细了解拦截器背后的机制,请阅读:

    【讨论】:

    • 谢谢!它现在确实有效。我实际上使用的是 4.3.6 版(也在我原来的问题中更新),并且错误为空。但现在在 4.4.6 版本上一切正常。
    • 我正要捕获错误消息,我正在研究如何在 API 请求成功完成时提取成功消息,例如状态码 200/201 等。我如何传递来自的 http 响应@ 987654326@ 如何将此响应返回到我提出请求的组件。我正在使用 ngrx 4
    • Angular6 中不再是这种情况,error.error 返回一个 Blob,而不是实际的正文字符串...
    • @reven,感谢您的信息,这意味着他们已修复它。
    • @MaxKoretskyiakaWizard 那么当 error.error 返回一个 blob 时如何从 HttpErrorResponse 获取正文?
    【解决方案2】:

    为了充分利用 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

    【讨论】:

      猜你喜欢
      • 2017-09-09
      • 2018-01-04
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2018-01-12
      • 1970-01-01
      • 2021-10-20
      • 2023-03-05
      相关资源
      最近更新 更多