Skip to content

Instantly share code, notes, and snippets.

@peterkeller
Last active April 24, 2021 08:08
Show Gist options
  • Save peterkeller/03355e05072a390faff8f006b71c3394 to your computer and use it in GitHub Desktop.
Save peterkeller/03355e05072a390faff8f006b71c3394 to your computer and use it in GitHub Desktop.
RxJS operator to handle errors
// https://stackoverflow.com/questions/52797992/which-rxjs-operator-to-choose-to-handle-http-errors-tap-or-catcherror/61836193#61836193
// "tap" is to cause side effects and it doesn't modify the chain at all, "catchError" is to catch errors in a stream and try to handle them.
http.get('https://test.com/').pipe(
tap(
() => {
// 200, awesome!, no errors will trigger it.
},
(error: HttpErrorResponse) => {
// error is here, but we can only call side things.
},
),
catchError(
(error: HttpErrorResponse): Observable<any> => {
// we expect 404, it's not a failure for us.
if (error.status === 404) {
return of(null); // or any other stream like of('') etc.
}
// other errors we don't know how to handle and throw them further.
return throwError(error);
},
),
).subscribe(
response => {
// 200 triggers it with proper response.
// 404 triggers it with null. `tap` can't make 404 valid again.
},
(error: HttpErrorResponse) => {
// any error except 404 will be here.
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment