Angular默认类errorHandler覆盖处理程序方法没有赶上一些错误,如400 Bad request或404 not found错误

问题描述 投票:-1回答:1

我试图创建一个简单实现角度自己的ErrorHandler类的类,其中我重写了方法处理程序(错误)函数,它捕获所有发生的错误。但是我观察到了一些错误: -

400坏请求

404未找到

这种方法不会引起错误。如何捕获这些错误以及用于记录目的。

javascript angular
1个回答
0
投票

您可以使用自定义HTTP拦截器。例如:

import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpResponse,
  HttpErrorResponse
} from '@angular/common/http';

import { Observable } from 'rxjs/Observable';

    @Injectable()
    export class CustomHttpInterceptor implements HttpInterceptor {

      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next
          .handle(req)
          .catch((err: HttpErrorResponse) => {
            if (err instanceof HttpErrorResponse) {
              // do something with incoming error
              // (you can find error status under err.status)
            }
            return Observable.throw(err);
          });
      }
    }

为了使其工作,将其添加到主app模块提供者数组:

{ provide: HTTP_INTERCEPTORS, useClass: CustomHttpInterceptor, multi: true }

© www.soinside.com 2019 - 2024. All rights reserved.