Angular httpClient interceptor error handling

痞子三分冷 提交于 2020-01-21 04:52:05

问题


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


回答1:


You should catch an error using 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);
            }
        }
}));



回答2:


You must pass the argument value to the do function of the stream, not create a new function inside it:

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



回答3:


Your error handler needs to return a 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:


It is off top, but Angular has better opportunity handle errors than interceptor. You can implement your own ErrorHandler. https://angular.io/api/core/ErrorHandler



来源:https://stackoverflow.com/questions/50999729/angular-httpclient-interceptor-error-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!