...

/

Error-Handling Patterns: Replace Strategy

Error-Handling Patterns: Replace Strategy

Learn about the replace strategy for error handling.

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.

Press + to interact
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', ...