Lessons34. catchError: a fallback instead of a crash
Lessons · 34
34. catchError: a fallback instead of a crash
catchError — catch and replace
When an error occurs in a stream, it "flies" top to bottom through the pipe until it meets a catchError. This operator works like this:
- It receives the error object.
- It must return a new Observable — something to replace the failed source.
- The subscriber then gets values from this new Observable, as if nothing had happened.
source$.pipe(
catchError(err => of('Fallback'))
)
// source$ failed → next('Fallback') → complete()
What a fallback is
A fallback is a safe value to lean on when there's an error: an empty list, default settings, a cached result. The goal is to keep the UI from "dying" and let it keep working with empty/safe data.
Your task
- After
map(...)insidepipe, addcatchError(error => of('Fallback value'))with a comma. - Expected output:
1, 2, 3, Fallback value, Complete. Notice:5never appears — the stream has already been replaced by the fallback.
Solution spoiler · click to reveal
const { of, map, catchError } = Rx;
const source$ = of(1, 2, 3, 4, 5);
const result$ = source$.pipe(
map(value => {
if (value === 4) {
throw 'Boom';
}
return value;
}),
catchError(error => {
return of('Fallback value');
})
);
result$.subscribe({
next: value => console.log(value),
error: error => console.log('Global Error: ' + error),
complete: () => console.log('Complete'),
}); script.ts
CONSOLE · Console output
Hit Run to see the result...