Skip to content

Function: catchError()

catchError<T>(handler): Operator<T, T>

Defined in: operators/catchError.ts:22

Creates a stream operator that catches errors from the source stream and handles them.

This operator listens for errors from the upstream source. When the first error is caught, it invokes a provided handler callback and then immediately completes the stream, preventing the error from propagating further down the pipeline.

  • Error Handling: The handler is executed only for the first error encountered.
  • Completion: After an error is caught and handled, the operator completes, terminating the stream's flow.
  • Subsequent Errors: Any errors after the first will be re-thrown.

This is useful for error-handling strategies where you want to perform a specific cleanup action and then gracefully terminate the stream.

Type Parameters

T

T = any

The type of the values emitted by the stream.

Parameters

handler

(error) => any

The function to call when an error is caught. It can return a void or a Promise<void>.

Returns

Operator<T, T>

An Operator instance that can be used in a stream's pipe method.

Examples

From catchError.spec.ts:11

typescript
let subject: Subject;

let handlerMock: jasmine.Spy = jasmine
  .createSpy('handlerMock')
  .and.returnValue(Promise.resolve(undefined));

subject = createSubject();
const error = new Error('Unhandled exception.');
const streamWithCatchError = subject.pipe(
  map(() => {
    throw error;
  }),
  catchError(handlerMock)
);
streamWithCatchError.subscribe({
  next: (value) => console.log(value),
  complete: () => {
    expect(handlerMock).toHaveBeenCalled();
    done();
  },
});
subject.next(1);
subject.complete();

Released under the MIT License.