RxJS Error Handling is not NEARLY understood enough.
Thread on RxJS error handling here 👇
1/8
There are two places to deal with errors:
1. In your subscribe call
2. In the stream (in a pipe() method)
2/8
For the subscribe method. Just pass in a second callback, this is your error handler. For @angular and most other uses, this is the place where you would take action based on the error, like displaying a message to the user, redirecting to a different screen/route, etc.
3/8
It looks like this:

.subscribe(
data => { // do something with the data},
err => { // handle the error }
)
4/8
For handling errors in the stream, there are 3 basic strategies:
1. Retry
2. Catch and rethrow
3. Catch and replace
5/8
For retrying, just call retry() and pass in a number of retries. I.e.

retry(2)

You can also pass in Infinity

retry(Infinity)
6/8
For catch and rethrow, you call catchError inside your pipe, then optionally inspect the error, then throw either the original error or a new error with more context.

catchError(err => {
if(err.status === 403) {
throw new Error(‘access denied’)
} else {
throw err;
}
})
7/8
For catch and replace, you return a new observable that Isn’t in an error state, and that becomes the new value(s) for subscribers

catchError(err => {
if(err.status === 408) {
// if timeout, use local cache
return of(myLocallyCachedData)
} else {
throw err;
}
})
8/8
You can follow @josepheames.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.