How to detect inside a stream if the subscribe defined an error handler

Viewed 42

Suppose I have the following

function getData() {
    return this.http.get('data');
}

...

getData().subscribe({
   complete: () => {
      this.closeDialog();
   });
}

Not tested, but I think this should work. However, the this.http call can throw an error. That can be fixed as follows

getData().subscribe({
   error: (err) => { this.showNotification(err) },
   complete: () => { this.closeDialog() }
});

or I could catch it inside getData

 function getData() {
    return this.http.get('data').pipe(catchError(err => {
        return of({});
    });
}

What I would like to do is:

  1. If the subscribe defines an error handler, don't catch the error inside getData
  2. If the subscribe doesn't define an error handler, catch the error inside getData

Is this possible? If not, I'm all ears to other suggestions/solutions!

1 Answers
  1. If the subscribe defines an error handler, don't catch the error inside getData
  2. If the subscribe doesn't define an error handler, catch the error inside getData

I don't understand about point 1, so I will talk about point 2. Well yeah for sure you can do that, in the end RxJS is just Javascript, so you can catch the error using try catch with the help of tap() operators. https://rxjs.dev/api/operators/tap.

Related