Search⌘ K

Error-Handling Patterns: Replace Strategy

Explore the replace strategy in RxJS error handling to manage stream errors by returning replacement observables. Understand how catchError intercepts errors, replacing the errored stream with fallback values to keep the reactive data flow uninterrupted.

Replace strategy

The error-handling function returns an observable, which is going to be a replacement observable for the stream that just errored out. This replacement observable is then going to be subscribed to, and its values are going to be used in place of the errored-out input observable.

TypeScript 4.9.5
const { from, of } = require('rxjs');
const { catchError, map } = require('rxjs/operators');
const stream$ = from(["5", "10", "6", "Hello", "2"]);
stream$
.pipe(
map((value) => {
if (isNaN(value)) {
throw new Error("This is not a number");
}
return parseInt(value);
}),
catchError((error) => {
console.log("Caught Error", error);
return of();
})
)
.subscribe({
next: (res) => console.log("Value Emitted", res),
error: (err) => console.log("Error Occurred", err),
complete: () => console.log("Stream Completed"),
});

Note: We’ll get the error “This is not a number” whenever a non-numeric input is given.

Let’s break down what’s happening at the level of this sample. We have an observable stream$ created from an array of string values, ['5', '10', ...