简体   繁体   中英

Why does Rxjs unsubscribe on error in the subscription callback?

I use RxJS 5.2.0 (yes, it's pretty old). I subscribe on some observable and I want to execute some code. If there is a js error in this code, then RxJS will just unsubscribe my subscriber and will not report an error into the console.

It looks very bad for me because the error will be hidden and I cannot see it and correct. Maybe, I already have some errors in my project, but I don't know about them.

The only way which I see is wrapping all code in my subscribers into try-catch. But it looks crazy, there are hundreds of such places.

I'm going to update RxJS in a couple of months but would be great to find some solution to this problem for now.

Here is an example on jsfiddle https://jsfiddle.net/Eugene_Ilyin/18kw3hde/

let subj = new Rx.BehaviorSubject(1);

subj.asObservable().subscribe(number => {
  console.log(number);
  let book;
  book.page();
  console.log(number);
});

setTimeout(() => {
  subj.next(2);
}, 1000);

There is a line book.page(); which provokes an error. But in a console of the browser, you will not see any error. After the error, the subscription will not be called again. Because it will be unsubscribed by RxJS, when it will catch an error by this code:

SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
    try {
        fn.call(this._context, value);
    }
    catch (err) {
        parent.syncErrorValue = err;
        parent.syncErrorThrown = true;
        return true;
    }
    return false;
};

This question could be related to my question. But there is a bit different situation and doesn't provide an answer.

try this out. You should put logics in operators, instead of inside subscribe. Take a look at this question rxjs. is it good practice to have code in subscribe method?

let subj = new Rx.BehaviorSubject(1);

subj.asObservable().do(()=>{
  console.log(number);
  let book;
  book.page();
  console.log(number);
}).catch(e => {
  console.error(e);
  return Rx.Observable.throw(e)
}).onErrorResumeNext()
  .subscribe(number => {
});

setTimeout(() => {
  subj.next(2);
}, 1000);

catch operator will catch you error and onErrorResumeNext() will keep the subscription.

https://jsfiddle.net/cvd7Lu4q/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM