How to trap errors from chained rxjs observables w

2019-02-27 11:20发布

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条回答
小情绪 Triste *
2楼-- · 2019-02-27 11:40

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.

查看更多
登录 后发表回答