
Scenario
When our Observable<E>
errors out, we want to emit the string fallback value OOOPS
.
Approach
oops.pipe(catchError(err => of('OOOPS')))
Demo
The first part of the demo uses throwError
to error out the catchMeIfYouCan:Observable<string>
, and therefore only the error
handler is called, and neither the next
nor the complete
handlers are called.
let catchMeIfYouCan: Observable<string> = throwError("Catch me if you can");catchMeIfYouCan.subscribe(() => console.log("Next handler will not execute"),e => console.log(e),() => console.log("Completion handler will not execute"));
In the second part we pipe
through catchError
and emit the fallback, and now both the next
and complete
handlers are called and the error
handler is not called.