【问题标题】:Angular 8 Intercept and modify Http Error ResponseAngular 8 拦截和修改 Http 错误响应
【发布时间】:2019-12-13 17:40:20
【问题描述】:

我需要拦截和修改一个 HttpResponse,它是 HttpErrorResponse 的实例,即状态:500,状态为 200 并填写其正文,以便我可以在我的 http.post 的 Observable 订阅中处理它作为成功的 http 调用。

【问题讨论】:

  • 欢迎来到 Stackoverflow,到目前为止你尝试过什么?任何要显示的代码..?

标签: angular http rxjs observable interceptor


【解决方案1】:

我设法使用以下拦截器修改了 HttpErrorResponse:

export class CustomErrorHttpInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).pipe(
      catchError((httpErrorResponse: HttpErrorResponse) => {

        // Customize as you wish:
        const newHttpErrorResponse = new HttpErrorResponse( {
          error: httpErrorResponse.error,
          headers: httpErrorResponse.headers,
          status: httpErrorResponse.status,
          statusText: httpErrorResponse.statusText,
          url: httpErrorResponse.url
        });

        return Observable.throw(newHttpErrorResponse);
      })
    );
  }
}

【讨论】:

    【解决方案2】:

    您可以使用 rxjs 中的 map 运算符和 catchError 来处理错误。代码如下:

    const withoutError = this.http
          .get("https://httpstat.us/500")
          .pipe(
              catchError((error) => {
              // here you can modify your error
              return of(error)
           })
          )
          .subscribe(res => {
            console.log("Run, because error has modified", res.status);
          }, (error) => {
            console.log('Never run ...')
          });
    

    https://httpstat.us/500 总是以 500 状态码响应。

    Here你可以看到它是如何工作的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-20
      • 2015-08-25
      • 1970-01-01
      相关资源
      最近更新 更多