Angular httpClient拦截器错误处理

时间:2018-06-23 09:18:34

标签: angular angular6 angular-http-interceptors angular-httpclient

在阅读了有关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, …}

5 个答案:

答案 0 :(得分:3)

您应该使用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);
            }
        }
}));

答案 1 :(得分:1)

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

答案 2 :(得分:1)

它是最重要的,但是Angular的机会处理错误比拦截器更好。 您可以实现自己的ErrorHandler。 https://angular.io/api/core/ErrorHandler

答案 3 :(得分:0)

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

答案 4 :(得分:0)

这是我正在使用的一些示例:

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