11

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

5 Answers 5

12

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>>();
    }));
Sign up to request clarification or add additional context in comments.

Comments

10

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

10 Comments

I get this error: TS2345: Argument of type '(err: any) => void' is not assignable to parameter of type '(err: any, caught: Observable<HttpEvent<any>>) => ObservableInput<{}>'. Type 'void' is not assignable to type 'ObservableInput<{}>'.
I just mentioned the syntax for catching errors. You should return the error or properly handle it in there. for ex you can do return Observable.throw(err); You could also change your return type to Observable<any> instead of Observable<HttpEvent<any>>
What should be the correct return result if I just want "nothing to happen" (ie, it wasn't an error) ?
I tried adding return Observable.empty<HttpEvent<any>>(), but I still get a ' EmptyError: no elements in sequence' printed in the console
|
1

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

2 Comments

I still don't get the 'nor this one' log.
Add a debugger inside the do, check what is the response that comes from the server and check why is not matching the two ifs.
0

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

3 Comments

It is the answer. Move to off Angular documentation, not only copy-paste.@ErikPhilips
How to implement it for handling network errors? The documentation doesn't has much for specific use case @Oleksii
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.