Skip to content
jshacks.dev
Async

The RxJS catchError Operator Explained With Examples

Learn how the RxJS catchError operator replaces a failed stream with a fallback, why placement decides whether the outer stream survives and how to rethrow.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Apache Kafka, RabbitMQ and Redis logos.

An observable that errors is finished. No more values arrive, the subscription ends and everything downstream sees the error. For a stream that should live for the whole session, such as a search box, a websocket feed or a polling loop, one failed request must not kill it. catchError is the operator that intercepts an error and decides what happens next: substitute a fallback value, switch to another observable, or throw a different error. The decision that matters most is where you put it, and the same operator in two positions produces two very different programs. This post explains catchError in RxJS 7 with printed output, shows both positions side by side, covers rethrowing and the caught argument, and lists the mistakes that cause silent failures.

What it does

catchError(selector) calls selector(error, caught) when the source errors. The function must return an observable, and the subscriber then receives that observable's values instead of the error.

JavaScript
import { of, throwError } from "rxjs";
import { catchError } from "rxjs/operators";

throwError(() => new Error("network down"))
  .pipe(catchError((err) => of(`fallback after: ${err.message}`)))
  .subscribe({
    next: (v) => console.log(v),
    complete: () => console.log("complete"),
  });
Text
fallback after: network down
complete

The error never reached the subscriber. The fallback observable emitted its value and completed, so the whole stream completed normally. Values emitted before the error pass through untouched.

JavaScript
import { concat, of, throwError } from "rxjs";
import { catchError } from "rxjs/operators";

concat(of(1, 2), throwError(() => new Error("x")), of(3))
  .pipe(catchError(() => of("recovered")))
  .subscribe(console.log);
Text
1
2
recovered

The 3 is gone. After an error, the source is dead, and catchError replaces the rest of it. It cannot resume the original stream.

Placement decides everything

Consider an input stream that triggers a request for each value. If a request fails, should the stream of inputs stop?

JavaScript
import { Subject, of, throwError } from "rxjs";
import { catchError, switchMap } from "rxjs/operators";

function request(term) {
  return term === "bad"
    ? throwError(() => new Error("server error"))
    : of(`results for ${term}`);
}

// catchError on the outer stream: dies after the first error
const outer$ = new Subject();
outer$
  .pipe(
    switchMap(request),
    catchError(() => of("outer fallback"))
  )
  .subscribe((v) => console.log("A:", v));

// catchError inside the projection: the outer stream survives
const inner$ = new Subject();
inner$
  .pipe(
    switchMap((term) =>
      request(term).pipe(catchError(() => of("inner fallback")))
    )
  )
  .subscribe((v) => console.log("B:", v));

for (const term of ["a", "bad", "c"]) {
  outer$.next(term);
  inner$.next(term);
}
Text
A: results for a
B: results for a
A: outer fallback
B: inner fallback
B: results for c

Stream A handled the error and then completed, so the input c produced nothing. Stream B caught the error inside the inner observable, so only that one request was replaced by a fallback, and the next input worked. For any long-lived stream with a flattening operator, the inner position is almost always the right one.

Rethrowing

Sometimes you want to log, translate or enrich an error and let it continue. Return throwError from the selector.

JavaScript
import { throwError } from "rxjs";
import { catchError } from "rxjs/operators";

throwError(() => ({ status: 500 }))
  .pipe(
    catchError((err) => {
      console.log("logging", err.status);
      return throwError(() => new Error(`request failed with ${err.status}`));
    })
  )
  .subscribe({ error: (e) => console.log("subscriber got:", e.message) });
Text
logging 500
subscriber got: request failed with 500

Rethrowing a wrapped error is a good place to turn a transport error into a domain error with a message a user can read.

The caught argument and self-retry

The second parameter is the source observable itself. Returning it resubscribes, which is the same as retry, but with the decision under your control.

JavaScript
import { defer, of, throwError } from "rxjs";
import { catchError } from "rxjs/operators";

let attempts = 0;

defer(() => {
  attempts += 1;
  return attempts < 3 ? throwError(() => new Error("not yet")) : of("ready");
})
  .pipe(
    catchError((err, caught) => {
      console.log(`attempt ${attempts} failed`);
      return caught;
    })
  )
  .subscribe(console.log);
Text
attempt 1 failed
attempt 2 failed
ready

Returning caught with no limit retries forever, so add a counter or a condition. For ordinary retries, retry({ count, delay }) is clearer.

Returning EMPTY to skip

If a failed item should simply be skipped, return EMPTY. The inner observable completes without a value, and the outer stream carries on.

JavaScript
import { EMPTY, from, of, throwError } from "rxjs";
import { catchError, mergeMap } from "rxjs/operators";

from([1, 2, 3])
  .pipe(
    mergeMap((n) =>
      (n === 2 ? throwError(() => new Error("bad")) : of(n * 10)).pipe(
        catchError(() => EMPTY)
      )
    )
  )
  .subscribe(console.log);
Text
10
30

Skipping silently is fine for optional enrichment and dangerous for data that matters. If the user must know, emit a marker value or log it.

Errors thrown inside operators

catchError also handles exceptions thrown by earlier operators, because RxJS converts a thrown exception inside map or tap into an error notification.

JavaScript
import { of } from "rxjs";
import { catchError, map } from "rxjs/operators";

of("1", "x", "3")
  .pipe(
    map((s) => {
      if (Number.isNaN(Number(s))) throw new Error(`not a number: ${s}`);
      return Number(s);
    }),
    catchError((e) => of(`caught ${e.message}`))
  )
  .subscribe(console.log);
Text
1
caught not a number: x

Again, 3 never arrives, since the error ended the source. To keep going after a bad value, catch inside a per-item inner observable instead.

Do not catch errors thrown by your own subscriber

An error thrown inside the next callback of subscribe is not routed through catchError. It is reported asynchronously as an unhandled error, since the stream's error channel is for source failures. Put logic that can throw into the pipe, not into the subscriber.

Common mistakes

Placing it at the end of a long-lived stream. One failure completes the stream. Move it inside the flattening operator's projection.

Swallowing errors. catchError(() => EMPTY) without logging hides bugs. Report the error somewhere before discarding it.

Returning a value instead of an observable. The selector must return an observable. Use of(value).

Retrying forever. Returning caught without a limit loops on a permanent failure.

Expecting it to resume the source. After an error the source is finished, and catchError only substitutes what comes next.

Deciding what a fallback means

A fallback value is a statement that the failure does not matter, and every catchError should be able to say why that is true. An empty list for an optional recommendations panel is a reasonable fallback, because the page is still useful. An empty list for the user's orders is a lie, because the user will think they have none. In the second case the better handler maps the error to an explicit error state, such as an object with a status of "error", and lets the template show a message and a retry button. The type system helps here: if the stream's value type is a union of data and error, nobody can forget to handle the error case.

Logging at the right layer

A common anti-pattern is to catch, log and swallow at every layer, so one failure produces five log lines, none of which have the context of the others. Log once, where you have the most information, usually at the boundary where the user-visible decision is made. Lower layers should let the error pass or wrap it with a cause and rethrow, and the top layer decides whether to show a message, retry or give up. This keeps logs searchable and keeps the lower layers reusable.

Retrying together with catchError

The two operators compose in a specific order. Place retry first, so transient failures are retried, and catchError after it, so the failure that survives all the retries is turned into a fallback or a user-facing error. Reversing the order means the catchError handles the first failure, returns a fallback, and the retry never sees an error at all.

Testing error paths

Error paths are the least exercised code in most applications, and catchError is where they live. Write tests that feed a failing source through the pipeline and assert on the fallback, and test the case where the fallback itself fails, since that second failure ends the stream in the way that surprises people. With TestScheduler, a marble such as --a--# describes a stream that emits and then errors, which makes these tests short.

A short checklist before you add one

Before adding a catchError, answer three questions. What should the user see if this fails? Should the stream keep running afterwards, and if so, is the handler inside the inner observable? And who needs to know, which decides what you log or report? If you can answer all three in a sentence, the handler is probably right, and if not, the operator is being used to silence a problem you have not understood yet.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.