‘catchError‘ and ‘finalize‘ are operators in RxJS, a reactive extensions library for JavaScript that uses Observables to manipulate and manage data streams. These operators are methods that can be applied to Observables to handle errors and perform actions when certain events occur.
1. ‘catchError‘ Operator:
‘catchError‘ is an operator used to handle errors within an observable stream. When an error occurs, instead of propagating the error and terminating the stream, catchError allows you to provide an alternative Observable or a function that resolves to an Observable. This new Observable replaces the error-producing one and the stream continues.
Example:
import { throwError, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
const observableWithError = throwError('An Error Occurred');
const observableWithFallback = of(42);
const result = observableWithError.pipe(
catchError(err => {
console.error('Error caught:', err);
return observableWithFallback;
})
);
result.subscribe(value => console.log('Value:', value));
In the example above, when the ‘throwError‘ Observable emits an error, the ‘catchError‘ operator catches it, logs the error to the console, and replaces the error-emitting Observable with ‘observableWithFallback‘.
Output:
Error caught: An Error Occurred
Value: 42
2. ‘finalize‘ Operator:
‘finalize‘ is an operator used to perform an action when an Observable completes or encounters an error. It does not handle or suppress the error like the ‘catchError‘ operator. It just performs side effects regardless of the stream’s completion or error status. It is similar to the ‘finally‘ block in a ‘try-catch-finally‘ statement.
Example:
import { of, throwError } from 'rxjs';
import { mergeMap, finalize } from 'rxjs/operators';
const source = of(1, 2, 3, 4, 5);
const result = source.pipe(
mergeMap(value => {
if (value === 4) {
return throwError('An Error Occurred at Value 4');
}
return of(value * 2);
}),
finalize(() => console.log('Stream Finalized'))
);
result.subscribe(
value => console.log('Value:', value),
err => console.error('Error:', err)
);
In the example above, when ‘mergeMap‘ encounters a value of 4, it emits an error using ‘throwError‘. The ‘finalize‘ operator listens for the completion or error of the Observable stream and performs its action regardless of the outcome.
Output:
Value: 2
Value: 4
Value: 6
Error: An Error Occurred at Value 4
Stream Finalized
As you can see from the examples, the ‘catchError‘ operator is used for handling and recovering from errors, while the ‘finalize‘ operator is used for performing actions when the stream completes or encounters an error.