Angular httpClient interceptor error handling

sarahwc5 picture sarahwc5 · Jun 23, 2018 · Viewed 19.1k times · Source

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

Answer

Amit Chigadani picture Amit Chigadani · Jun 23, 2018

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