In your example the catch would be invoked if an error occurred. Additionally, the map
operator does not have a second argument so that function will never be called. If you have an error handler on a subscribe then the callback will be invoked if an unhandled exception occurs. The catchError
operator is a way of handling errors. It basically acts as a switchMap
to switch to a new observable stream.
Examples:
Subscribe Error Handler (Demo)
return throwError('This is an error!').subscribe(data => {
console.log("Got Data: ", data);
}, error => {
console.error('error', error); // Observable stream has error so this prints
});
Catching an error (Demo)
return throwError('This is an error!').pipe(
catchError(error => {
console.log("Error Caught", error);
return of(2); // Catches the error and continues the stream with a value of 2
}),
).subscribe(data => {
console.log("Got Data: ", data); // Data will be logged
}, error => {
console.error('error', error); // Will not be called
});
Catching an error and re-throwing (Demo)
return throwError('This is an error!').pipe(
catchError(error => {
console.log("Error Caught", error);
return throwError(error); // Catches the error and re-throws
}),
).subscribe(data => {
console.log("Got Data: ", data);
}, error => {
console.error('error', error); // Observable stream has error so this prints
});