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

2

8

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?

Peppercorn answered 4/10, 2018 at 18:3 Comment(2)
This case there will be an error, since RxJS is about observables which should be subscribed to.Narial
Also, why do you ask 'what will be invoked' meanwhile you can just try it yourself? Nothing crucial will happen to you.Narial
L
14

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
});
Leverrier answered 4/10, 2018 at 18:22 Comment(1)
what about catch and catchError, is it much different?Tai
D
1

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.

Destructor answered 4/10, 2018 at 18:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.