← Back to Angular, page 3

angular-0045 · Hard senior

How do you handle errors in RxJS streams with catchError and retry, and what do shareReplay and its refCount option do?

An error ends an Observable, so catchError must sit where it can recover without killing the outer stream, usually inside the flattening operator. retry can resubscribe with a count and a delay function for backoff. shareReplay shares one execution between subscribers and replays the last value, and refCount lets it stop the source when nobody listens.

Full answer

In RxJS an error is terminal. After error, the stream emits nothing more. This has a big consequence for long-lived streams such as a search box.

Where to put catchError: on the inner Observable. If you write search$.pipe(switchMap(q => http.get(q)), catchError(...)), one failed request ends the whole search stream and the box stops working. Writing search$.pipe(switchMap(q => http.get(q).pipe(catchError(() => of([]))))) handles the error and keeps the outer stream alive. The example below shows both: the inner version gives 1, -1, 3, and the outer version stops at 1, -1.

Retry. retry(3) resubscribes immediately, which can hammer a failing server. Use the config form: retry({ count: 3, delay: (error, attempt) => timer(2 ** (attempt - 1) * 100) }). This waits 100 ms, 200 ms, then 400 ms (exponential backoff). Only retry errors that make sense to retry (network errors, status 503), not a 400 or 401, and only for requests that are safe to repeat (GET, or idempotent calls).

Sharing. A cold Observable such as http.get(...) runs again for every subscriber. If two parts of the page subscribe, two requests go out. shareReplay({ bufferSize: 1, refCount: true }) runs the source once, caches the last value for late subscribers, and with refCount: true unsubscribes from the source when the last subscriber leaves. Without refCount the source subscription can stay alive (a possible leak for infinite sources). share() shares without replaying, and connectable/Subject are lower-level tools.

Also useful: finalize for cleanup that runs on complete, error, or unsubscribe; tap({ error }) for logging without changing the stream; and throwError(() => err) to rethrow after logging.

typescript
import {
  catchError,
  concatMap,
  defer,
  finalize,
  from,
  lastValueFrom,
  of,
  retry,
  shareReplay,
  throwError,
  timer,
  toArray,
} from 'rxjs';

// 1. Retry with backoff: fails twice, then succeeds.
let attempts = 0;
const flaky$ = defer(() => {
  attempts++;
  return attempts < 3 ? throwError(() => new Error('network down')) : of('data loaded');
});

const withRetry$ = flaky$.pipe(
  retry({ count: 3, delay: (_error, attempt) => timer(10 * 2 ** (attempt - 1)) }),
);
console.log('1.', await lastValueFrom(withRetry$), 'after', attempts, 'attempts');

// 2. Inner catchError keeps the outer stream alive; outer catchError ends it.
const mayFail = (n: number) => (n === 2 ? throwError(() => new Error('bad ' + n)) : of(n));

const inner = await lastValueFrom(
  from([1, 2, 3]).pipe(
    concatMap((n) => mayFail(n).pipe(catchError(() => of(-1)))),
    toArray(),
  ),
);
const outer = await lastValueFrom(
  from([1, 2, 3]).pipe(
    concatMap((n) => mayFail(n)),
    catchError(() => of(-1)),
    toArray(),
  ),
);
console.log('2. inner catchError:', inner); // [ 1, -1, 3 ]
console.log('2. outer catchError:', outer); // [ 1, -1 ]

// 3. Sharing one execution between two subscribers.
let calls = 0;
const source$ = defer(() => {
  calls++;
  return of('response');
});
const shared$ = source$.pipe(shareReplay({ bufferSize: 1, refCount: true }));

await lastValueFrom(source$);
await lastValueFrom(source$);
console.log('3. calls without sharing:', calls); // 2

calls = 0;
await lastValueFrom(shared$);
await lastValueFrom(shared$);
console.log('3. calls with shareReplay:', calls); // 1

// 4. finalize runs on completion.
await lastValueFrom(of('x').pipe(finalize(() => console.log('4. cleanup done'))));

Tested with RxJS 7 under Node 22.18 or newer (`node main.ts`, package.json with `type: module`), run twice with identical output. Delays are 10 ms and 20 ms so the script finishes quickly.

Key points

  • An error terminates the stream, so put `catchError` inside `switchMap` or `mergeMap`.
  • `retry` takes `{ count, delay }`; use backoff and retry only safe, transient failures.
  • `shareReplay({ bufferSize: 1, refCount: true })` makes one execution and replays the latest value.
  • `finalize` runs on complete, error, and unsubscribe.

Common mistakes

  • Placing `catchError` on the outer stream of an event source, which silently ends it after the first error.
  • Retrying immediately and forever, which turns a small outage into a bigger one.
  • Using `shareReplay(1)` without `refCount` on a long-lived source, which keeps it running.

Follow-ups

  • Which HTTP errors would you retry, and which would you not?
  • What is the difference between `share()` and `shareReplay()`?
  • How would you show an error message but still keep the stream alive?

Tips

  • Show the inner versus outer `catchError` difference with numbers. It proves understanding.
  • Mention idempotency when talking about retry.
  • Name `refCount`. Many candidates only know `shareReplay(1)`.

Evaluation rubric

  • Explains terminal errors and catchError placement.
  • Writes a retry with backoff and limits.
  • Explains shareReplay and refCount.