简体   繁体   English

Angular httpClient 拦截器错误处理

[英]Angular httpClient interceptor error handling

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

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 错误 HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "OK", url: " http://localhost:8080/test ", ok: false, ...}

Your error handler needs to return a new Observable<HttpEvent<any>>()您的错误处理程序需要返回一个new Observable<HttpEvent<any>>()

return next.handle(request)
    .pipe(catchError((err: any) => {
        console.log('this log isn't');
        if (err instanceof HttpErrorResponse) {
            if (err.status === 401) {
                console.log('Unauthorized');
            }
        }

      return new Observable<HttpEvent<any>>();
    }));

You should catch an error using catchError您应该使用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);
            }
        }
}));

You must pass the argument value to the do function of the stream, not create a new function inside it:您必须将参数值传递给流的 do 函数,而不是在其中创建新函数:

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!');
            }
        }
    });

It is off top, but Angular has better opportunity handle errors than interceptor.它不是最重要的,但是 Angular 比拦截器有更好的机会处理错误。 You can implement your own ErrorHandler.您可以实现自己的 ErrorHandler。 https://angular.io/api/core/ErrorHandler https://angular.io/api/core/ErrorHandler

here some example I'm using:这里有一些我正在使用的例子:

export class ErrorHandlerInterceptor implements HttpInterceptor {

    intercept(
        request: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpEvent<any>> {
        const loadingHandlerService = this.inej.get(LoadingHandlerService);
        const errorHandlerService = this.inej.get(ErrorHandlerService);

        return next.handle(request)
            .pipe(
                catchError(err => {
                    loadingHandlerService.hideLoading();
                    if (err instanceof HttpErrorResponse) { errorHandlerService.handleError(err) }
                    return new Observable<HttpEvent<any>>();
                })
            );
    }

    constructor(private inej: Injector) { }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM