我在我的应用中实现了一个全局错误处理程序。我目前的问题是它正在拦截与客户端相关的错误,但是不拦截http调用的任何服务器错误。这就是错误处理程序实现的样子:
import { Injectable, ErrorHandler, Injector } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { NotificationService } from '@app/services/notification.service';
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
constructor(private _injector: Injector) { }
handleError(error: Error | HttpErrorResponse) {
const notificationService: this._injector.get(NotificationService);
if (error instanceof HttpErrorResponse) {
// Server error happened (this DOES NOT get intercepted)
if (!navigator.onLine) {
// No Internet connection
return notificationService.notify('No Internet Connection');
}
// Http Error (this DOES NOT get intercepted)
return notificationService.notify(`${error.status} - ${error.message}`);
} else {
// Client Error Happend (this gets intercepted)
console.error(error);
}
// Log the error anyway
console.error(error);
}
}
我在 GlobalErrorHandler
中提供 AppModule
,如下所示:
providers: [
{ provide: ErrorHandler, useClass: GlobalErrorHandler}
]
处理程序没有截获 http 错误的任何想法?