Course contentsShow
← JavaScript
Lesson 2135 of 2,72344. Reactive PatternsFree lesson

Error Handling in Streams

Using `catchError` and `retry` operators to handle and recover from errors.

Error Handling in Streams

What You'll Learn

You'll learn how to use catchError and retry operators to gracefully handle and recover from errors in RxJS observable streams.

Errors in Reactive Streams

When working with observables, errors can occur at any point in the stream—during data fetching, transformation, or processing. Unlike synchronous code where a single try-catch handles errors, streams need operators that let you intercept, handle, and potentially recover from errors while keeping the stream alive.

Think of it like a conveyor belt in a factory: if one item causes a problem, you want to either fix it on the spot, replace it with a backup, or try the operation again—without shutting down the entire production line.

The catchError Operator

catchError intercepts errors and lets you return a fallback observable or value. It prevents errors from terminating your subscription unexpectedly:

import { of, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

const source$ = throwError(() => new Error('API failed'));

source$.pipe(
  catchError(error => {
    console.log('Caught:', error.message);
    return of({ data: 'default value' }); // Fallback observable
  })
).subscribe(value => console.log(value));
// Logs: "Caught: API failed"
// Then: { data: 'default value' }

The retry Operator

retry automatically resubscribes to the source observable when an error occurs, attempting the operation again:

import { throwError } from 'rxjs';
import { retry } from 'rxjs/operators';

let attempt = 0;

const unstable$ = throwError(() => {
  attempt++;
  return new Error(`Attempt ${attempt} failed`);
});

unstable$.pipe(
  retry(2) // Try 2 more times after initial failure
).subscribe({
  error: err => console.log('Final error:', err.message)
});
// Tries 3 times total (1 initial + 2 retries)

Key Takeaway: Use catchError to provide fallback values or alternative streams when errors occur, and retry to automatically reattempt operations—together, they make your reactive streams resilient to temporary failures.