Angular httpClient拦截器错误处理

Angular httpClient interceptor error handling

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

在控制台日志上,我也得到了这个:

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, …}

您必须将参数值传递给流的 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!');
            }
        }
    });

您应该使用 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 比拦截器有更好的机会处理错误。 您可以实现自己的 ErrorHandler。 https://angular.io/api/core/ErrorHandler

您的错误处理程序需要 return 一个 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>>();
    }));

这里是我使用的一些例子:

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) { }
}