Error Notification
The error notification is one of the three notification types, and one of the optional properties for an Observer when subscribing to an Observable. An error notification is a signal to indicate that an error has occurred in either the production of values in a cold Observable or within an operator.
There are a few ways to be notified about the occurrence of an error:
- The Observer's error handler.
- The
catchError
operator. - The
retry()
andretryWhen()
operators.
It is also important to understand that error notification is part of your contract with an Observable and the operators available in RxJS. If an error occurs you need an effective way to handle errors, throw errors, retry upon error, and execute code regardless of whether an error has occurred or is caught.
Finally, we should also understand that when an error occurs the Observable has ended. Therefore, Observers will receive the error notification and will not receive any further notifications, including the completion notification.
Observer's error
Property
The Observer's error
property enables us to catch an error.
The Observer's error
property is a function that will be invoked with the error, which may be an JavaScript Error object, but can be any error value that is emitted by the source Observable.
It is important to note that the Observer's error
property:
- is last to be notified of an error, perhaps except for the
finalize()
operator, however thefinalize()
operator does not receive the error notification value. - is not able to retry or modify the error notification value.
Let's quickly look an example:
const observable = new Observable((observer: Observer<number>) => {
throw new Error('Oops!');
observer.next(1);
});
observable.subscribe({
next: (value) => console.log(value),
error: (e) => console.error(e),
complete: () => console.log('complete')
});
Let's review the code above:
- First, we are creating a new cold Observable.
- When the consumer subscribes to the Observable it will immediately
throw
a newError
. - We are not using
catchError()
so thatObserver
is notified of the error notification. - As expected, the
error
function is invoked with the error value, which we are then usingconsole.error()
to log the error. - When we run this code we should see a single error message displaying in the console.
What about try...catch
?
Good question.
When using Observables we should not use the try...catch
operators.
This is because all error cases are asynchronous.
This means that try/catch will not be able to catch an error that occurs in either the production of next notification values in a cold Observable or within an operator that accepts a function.
To reiterate, part of the contract when using Observables with RxJS is that the Observable will catch runtime exceptions and emit an error notification that we can then appropriate respond to.