Angular 8 拦截和修改Http错误响应

标签 angular http rxjs observable interceptor

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

最佳答案

我设法使用以下拦截器修改了 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);
      })
    );
  }
}

关于Angular 8 拦截和修改Http错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59327417/

相关文章:

angular - 立即调用函数并每隔 X 秒调用一次函数

javascript - rxjs Observable.if 在使用 map 时总是执行这两个语句

javascript - 将身份验证服务与 AuthGuard 连接(简单问题)

子模块的 Angular 合并路线

javascript - 为什么在这种情况下combineLatest运行但forkJoin失败

java - 检查对服务器的所有请求的有效负载

git - 如何从私有(private) Github 存储库下载二进制文件?

通过 API 的 Facebook 智能好友列表

node.js - 无法在 Angular 项目中使用 rxjs 的 map 运算符

Angular Select with ngFor 更改第一个选择会影响第二个选择