Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: intercept HTTP errors and continue chain

Tags:

angular

rxjs

I want to treat certain HTTP error codes as non-errors, and handle their responses normally. So I tried adding an HttpInterceptor to catch 500 status codes, and return the original response (which Angular puts in error.error):

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.status === 500) {
          return of(error.error);
        } else {
          return throwError('server error');
        }
      })
    );
  }

But then if there's an error, anything that I had piped to my http request doesn't get executed. For example, if I do this, the log statement doesn't happen:

this.http.get(...).pipe(
  tap(console.log)
)

How can I make this work?

Here's a sample...it never logs "got result" from AppComponent.

like image 579
JW. Avatar asked Mar 15 '26 15:03

JW.


1 Answers

Your chain stops working since Angular http module filters messages that it receives from interceptor:

const res$: Observable<HttpResponse<any>> = <Observable<HttpResponse<any>>>events$.pipe(
        filter((event: HttpEvent<any>) => event instanceof HttpResponse));

As you can see you should return stream of HttpResponse class like:

import { HttpResponse, ... } from '@angular/common/http';
...

if (error.status === 404) {
  console.log('caught', error.error);

  return of(new HttpResponse({
    body: error.error
  }));
}

Forked Stackblitz

like image 125
yurzui Avatar answered Mar 17 '26 05:03

yurzui