If I have code like the below:
const d: any = {};
return this.http.post(url, body, httpOptions).map(data => {
return d;
}, error => {
console.error('error');
})
.catch((err, d$) => {
return Observable.of(d);
});
and if there is any kind of error i.e. the POST request failed or some error in the .map()
success callback or any other kind of error.
Which of the two error handlers would be invoked the error callback on the .map()
or the .catch()
callback? Is it dependent on the type of the error that might happen?
Would the error callback on the .map()
be skipped always because of the presence of the .catch()
operator?
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.
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
});
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
});
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
});
To be honest - I never seen such syntax and I asume its wrong:
.map(data => {
return d;
}, error => {
error
is one of the three Observable's subscribe()
method callbacks. It fires once - if error happens. But Rxjs catch
operator returns an Observable. Thats the main difference - you can relay on it to continue your stream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With