Angular httpClient interceptor error handling

前端 未结 5 980
滥情空心
滥情空心 2021-02-15 23:45

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:

<
相关标签:
5条回答
  • 2021-02-16 00:11

    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) { }
    }
    
    0 讨论(0)
  • 2021-02-16 00:15

    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!');
                }
            }
        });
    
    0 讨论(0)
  • 2021-02-16 00:24

    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>>();
        }));
    
    0 讨论(0)
  • 2021-02-16 00:27

    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

    0 讨论(0)
  • 2021-02-16 00:32

    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);
                }
            }
    }));
    
    0 讨论(0)
提交回复
热议问题