我有一个全局 HttpInterceptor,它带有一个处理 HttpErrorResponse 的 catch block 。但我的要求是,当服务进行 http 调用并且还有错误处理程序时,我希望服务上的错误处理程序首先关闭。如果此服务上没有错误处理程序,那么我希望全局 HttpInterceptor 错误处理程序来处理它。
示例代码:
HTTP拦截器:
@Injectable()
export class ErrorHttpInterceptor implements HttpInterceptor {
constructor(private notificationService: NotificationService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req)
.catch(
error => {
if (error instanceof HttpErrorResponse) {
this.notificationService.error('Error', 'Error in handling Http request');
}
return Observable.empty<HttpEvent<any>>();
}
);
}
}
服务调用:
updateUser(id, data) {
return this.http
.patch(`${API.userUrl}/${id}`, {data: data})
.subscribe(
() => console.log('success'),
(err) => this.notificationService.error('custom code to handle this')
);
}
在这种情况下,ErrorHttpInterceptor 会发出通知,然后 userService 错误处理也会发出错误通知。
但在我的用例中,我希望 ErrorHttpIntercetor 仅在底层订阅未处理错误时才处理错误。有办法做到这一点吗?
最佳答案
解决方法之一是通过请求传递httpHeaders
:
request() {
const url = 'GoalTree/GetById/';
let headers = new HttpHeaders();
headers = headers.append('handleError', 'onService');
this.http.get(url, {headers: headers})
.pipe(
map((data: any) => {
this.showError = false;
}),
catchError(this.handleError)
)
.subscribe(data => {
console.log('data', data);
})
}
拦截器.ts:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.spinnerService.show();
return next.handle(req).do(
(event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
this.spinnerService.hide();
}
},
(err: any) => {
if (req.headers.get('handleError') === 'onService') {
console.log('Interceptor does nothing...');
} else {
console.log('onInterceptor handle ', err);
}
}
);
}
并在拦截器
的错误回调中检查请求 header 。
但是在这个解决方案中,拦截器在任何服务调用之前处理请求。
关于Angular 5 HttpInterceptor 错误处理首先调用调用者的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49740933/