Angular httpClient拦截器错误处理 [英] Angular httpClient interceptor error handling
本文介绍了Angular httpClient拦截器错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在阅读了有关http客户端错误处理的有关角度的文档之后,我仍然不明白为什么我没有使用以下代码从服务器捕获401错误:
after reading the documentation on angular about http client error handling, I still don't understand why I don't catch a 401 error from the server with the code below:
export class interceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('this log is printed on the console!');
return next.handle(request).do(() => (err: any) => {
console.log('this log isn't');
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
console.log('nor this one!');
}
}
});
}
}
在控制台日志上,我也得到了:
on the console log, I also get this:
zone.js:2969 GET http://localhost:8080/test 401()
core.js:1449错误HttpErrorResponse {headers:HttpHeaders,状态:401,statusText:"OK",url:" http://localhost:8080/test ",确定:false,...}
core.js:1449 ERROR HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "OK", url: "http://localhost:8080/test", ok: false, …}
推荐答案
您应该使用catchError
return next.handle(request)
.pipe(catchError(err => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
console.log('this should print your error!', err.error);
}
}
}));
这篇关于Angular httpClient拦截器错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文