我试图创建一个简单实现角度自己的ErrorHandler类的类,其中我重写了方法处理程序(错误)函数,它捕获所有发生的错误。但是我观察到了一些错误: -
400坏请求
和
404未找到
这种方法不会引起错误。如何捕获这些错误以及用于记录目的。
您可以使用自定义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 }