我正在尝试实现错误处理程序。
如果我手动抛出错误,则处理程序可以正常工作,但是服务器响应错误会更新。
这是一个实现:
import {ErrorHandler, Injectable, Injector} from '@angular/core';
import {AuthenticationService} from './authentication.service';
@Injectable({
providedIn: 'root'
})
export class AppErrorHandlerService implements ErrorHandler {
constructor(private injector: Injector) {
}
handleError(error: any): void {
console.error('handleError()');
const auth = this.injector.get(AuthenticationService);
if (error.status === 401 || error.status === 403) {
alert('Your session has expired');
auth.logout();
} else {
alert('Error has occur. Message=' + error.message);
}
}
}
提供商:
providers: [
AppErrorHandlerService,
{
provide: ErrorHandler,
useClass: AppErrorHandlerService
}
]
每当我从服务器获得403时,它就会进入控制台而不是来自自定义错误处理程序。
我不确定,但也许它与请求拦截器有关:
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private injector: Injector) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const auth = this.injector.get(AuthenticationService);
const authHeaders = auth.getAuthHeader();
const authReq = request.clone({headers: authHeaders});
return next.handle(authReq);
}
}