Angular httpClient 拦截器错误处理 [英] Angular httpClient interceptor error handling

查看:45
本文介绍了Angular httpClient 拦截器错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了有关 http 客户端错误处理的 angular 文档后,我仍然不明白为什么我没有使用以下代码从服务器捕获 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()

zone.js:2969 GET http://localhost:8080/test 401 ()

core.js:1449 ERROR HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "OK", url: "http://localhost:8080/test", ok: 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆