10

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

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
sarahwc5
  • 391
  • 3
  • 4
  • 10

5 Answers5

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>>();
    }));
Tito Leiva
  • 892
  • 1
  • 12
  • 29
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);
            }
        }
}));
Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98
  • 1
    Read more about it here https://angular.io/guide/http#getting-error-details – Amit Chigadani Jun 23 '18 at 11:17
  • 10
    I get this error: TS2345: Argument of type '(err: any) => void' is not assignable to parameter of type '(err: any, caught: Observable>) => ObservableInput<{}>'.   Type 'void' is not assignable to type 'ObservableInput<{}>'. – sarahwc5 Jun 23 '18 at 11:42
  • 1
    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` instead of `Observable>` – Amit Chigadani Jun 23 '18 at 11:45
  • 1
    What should be the correct return result if I just want "nothing to happen" (ie, it wasn't an error) ? – sarahwc5 Jun 23 '18 at 11:51
  • I tried adding `return Observable.empty>()`, but I still get a ' EmptyError: no elements in sequence' printed in the console – sarahwc5 Jun 23 '18 at 12:10
  • If you don't want to throw any error, then simply return Observable.empty() or Observable.of(false) – Amit Chigadani Jun 23 '18 at 12:45
  • When using a Observable.empty(), I still get a 'GET http://localhost:8080/test 403 ()' log in my console log.How can I avoid it? – sarahwc5 Jun 23 '18 at 14:41
  • Though it feels this is normal behaviour. Although I still get a EmptyError: no elements in sequence when I load the page. Where can it come from ? – sarahwc5 Jun 23 '18 at 15:20
  • I'll create a new question and close this one then, thanks. ==> https://stackoverflow.com/questions/51002928/rxjs-emptyerror-no-elements-in-sequence – sarahwc5 Jun 23 '18 at 16:14
  • `Observable.empty()` is deprecated. Your error handler must to return a `new Observable>()` instead – Tito Leiva May 13 '19 at 09:03
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!');
            }
        }
    });
Daniel Caldera
  • 1,069
  • 1
  • 9
  • 17
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

Oleksii
  • 59
  • 6
  • 1
    [When someone goes on Stack Exchange, the question "answer" should actually contain an answer. Not just a bunch of directions towards the answer.](https://meta.stackexchange.com/a/8259/171858). – Erik Philips Jul 10 '19 at 13:34
  • 2
    It is the answer. Move to off Angular documentation, not only copy-paste.@ErikPhilips – Oleksii Jul 15 '19 at 23:53
  • How to implement it for handling network errors? The documentation doesn't has much for specific use case @Oleksii – Black Mamba Jun 11 '20 at 17:31
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) { }
}
Muhammed Moussa
  • 4,589
  • 33
  • 27