Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In RxJS what's the difference between error callback vs .catch()?

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?

like image 685
Shikasta_Kashti Avatar asked Oct 04 '18 18:10

Shikasta_Kashti


2 Answers

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
});
like image 95
Teddy Sterne Avatar answered Sep 20 '22 10:09

Teddy Sterne


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.

like image 32
Julius Dzidzevičius Avatar answered Sep 20 '22 10:09

Julius Dzidzevičius