The old way of catching errors in RxJS was a method per subscription like so. Imagine an app using a http service to get some data
class yourHttpClient {
get<T>() : Observable<T> {
return this.http.get<T>('endpoint');
}
}
yourHttpClient.get().subscribe(() => {
// Your logic
},
(error) => {
console.log(error);
}
);
The downside to this is that every subscription needs to catch the errors and handle them accordingly.
The catchError pipe
Instead we can use the catchError pipe in the HttpClient itself to handle our errors. As you can see in the catchError RxJS pipe the error is logged and returned and you no longer need error logic when creating the subscriptions
class yourHttpClient {
get<T>() : Observable<T> {
return this.http.get<T>('endpoint').pipe(
catchError((error) => {
console.log(error);
return error;
})
}
}
yourHttpClient.get().subscribe(() => {
// Your logic
}
);
Looking at this example we can improve it a bit more, we know we only get a single result from the get method. So we can add the first()
operator to the get request to close the subscription
class yourHttpClient {
get<T>() : Observable<T> {
return this.http.get<T>('endpoint').pipe(
catchError((error) => {
console.log(error);
return error;
}),
first()
}
}
Top comments (0)