How to trap errors from chained rxjs observables when using combineLatest?

最后都变了- 提交于 2019-12-20 03:40:08

问题


Following on from this post, I have the following

Observable.combineLatest(
        this.translate.get("key1"),
        this.translate.get(""),
        this.translate.get("key3"),
        this.translate.get("key4")
    )
    .subscribe(([result1, result2, result3, result4]) => {
        console.log(result1);
        console.log(result2);
        console.log(result3);
        console.log(result4);
    },
      error => {
        console.log(`${error}`);            
   });  

At line 2 I get an error, but this does not seem to go into the error handler above. Unfortunately the examples and doco I find don't seem to include how to catch errors (assume the above would work).

Does anyone have any ideas on how to do this?


回答1:


It seems likely to me that this.translate.get("") is validating an argument and is throwing 'outside' of the observable (i.e. before it even creates its observable).

You can verify the error handling using code like this:

import "rxjs/add/observable/throw";

Observable.combineLatest(
  this.translate.get("key1"),
  Observable.throw(new Error("Boom!")),
  this.translate.get("key3"),
  this.translate.get("key4")
)
.subscribe(
  ([result1, result2, result3, result4]) => {
    console.log(result1);
    console.log(result2);
    console.log(result3);
    console.log(result4);
  },
  error => {
    console.log(`${error}`);
  }
);

And you can verify that this.translate.get("") is throwing the error 'outside' of the observable like this:

import "rxjs/add/observable/defer";

Observable.combineLatest(
  this.translate.get("key1"),
  Observable.defer(() => this.translate.get("")),
  this.translate.get("key3"),
  this.translate.get("key4")
)
.subscribe(
  ([result1, result2, result3, result4]) => {
    console.log(result1);
    console.log(result2);
    console.log(result3);
    console.log(result4);
  },
  error => {
    console.log(`${error}`);
  }
);

If this is what it is doing, I guess it's reasonable behaviour, as it's rather unlikely an empty key is valid. Errors that are more 'internal' are likely to be reported via the observable and should be handled by the error callback you've passed to subscribe.



来源:https://stackoverflow.com/questions/41755718/how-to-trap-errors-from-chained-rxjs-observables-when-using-combinelatest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!