catch / catchError
signature: catchError(project: (err: any, caught: Observable<T>) => ObservableInput<any>): Observable
catchError(project: (err: any, caught: Observable<T>) => ObservableInput<any>): ObservableGracefully handle errors in an observable sequence.
💡 Need to retry a failed operation? Check out retry or retryWhen!
💡 For resource cleanup regardless of error, use finalize!
⚠ Remember to return an observable from the catchError function!
Why use catchError?
Think of catchError as your observable's safety net. When your stream encounters an error, whether from a failed HTTP request, unexpected data, or any other issue, catchError gives you a chance to recover gracefully instead of letting your entire observable sequence crash and burn. It's the difference between your app showing a friendly "Something went wrong" message versus a blank screen.
What makes catchError particularly valuable is its flexibility in how you respond to errors. You can provide fallback data from a cache, you can transform errors into user-friendly messages, or you can even decide to retry the operation (though retry is usually better for that). The key insight is understanding where you place catchError in your operator chain. Put it at the outer level and your entire stream ends when an error occurs, but place it inside operators like switchMap and only that inner operation fails while your stream continues.
In essence, catchError keeps your reactive applications resilient by ensuring that errors are handled on your terms, not left to crash your user experience.
Examples
Example 1: Catching error from observable
( StackBlitz )
Example 2: Catching rejected promise
( StackBlitz )
Example 3: Catching errors comparison when using switchMap/mergeMap/concatMap/exhaustMap
( StackBlitz )
Example 4: Providing fallback data on HTTP error
( StackBlitz )
Related Recipes
Additional Resources
catchError 📰 - Official docs
Error handling operator: catch 🎥 💵 - André Staltz
Error Handling in RxJS 📰 - Angular University
📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/packages/rxjs/src/internal/operators/catchError.ts
Last updated