CSchulz
CSchulz

Reputation: 11040

Subscriber should not stop on error in observable

I am struggling with a subscriber, which automatically unsubscribe itself on error:

observable
  .subscribe(
    (data) => {
      // some logic encountering an error during execution
      // comparable to throw new Error()
    }
  )

I can prevent it with using try / catch:

observable
  .subscribe(
    (data) => try { 
        // some logic encountering an error during execution
        // comparable to throw new Error()
      } catch(e) {
      }
  )

But it feels like a work around.

I have dived into the source of Subscriber and SafeSubscriber, which automatically call unsubscribe on error:

  private __tryOrUnsub(fn: Function, value?: any): void {
    try {
      fn.call(this._context, value);
    } catch (err) {
      this.unsubscribe();
      throw err;
    }
  }

Is the only way to prevent this behavior to implement an own Subscriber or using try / catch?

Upvotes: 6

Views: 3997

Answers (1)

martin
martin

Reputation: 96999

That's correct behavior. You can use the catch() operator to subscribe to the same source Observable again (or a different one on error).

source
  .catch(err => Observable.of(null))
  .subscribe(...);

This will just return null in the next handler instead of the original error.

Also note that any exception is rethrown if the subscriber doesn't have any error handler.

For example to just avoid throwing an error you could make:

source
  ...
  .subscribe(..., error => {});

However this will always unsubscribe the chain because this is one of the basic principles of Observables. They emit zero or more next notifications and one complete or error notification but never both.

It's hard to tell what problem are you trying to solve where you don't want to unsubscribe, sometimes you can use Subject and only pass it next notifications and ignore the rest...:

const subject = new Subject();
source.subscribe(val => subject.next(val));

subject.subscribe(...);

Upvotes: 3

Related Questions