使用combineLatest时如何从链接的rxjs observables中捕获错误? [英] How to trap errors from chained rxjs observables when using combineLatest?

查看:15
本文介绍了使用combineLatest时如何从链接的rxjs observables中捕获错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇文章之后,我有以下

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}`);            
   });  

在第 2 行我收到一个错误,但这似乎没有进入上面的 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?

推荐答案

在我看来,this.translate.get("") 很可能是在验证一个论点,并将其抛出到可观察对象的外部"(即在它甚至创建其可观察对象之前).

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}`);
  }
);

您可以验证 this.translate.get("") 是否将错误抛出到 observable 的外部",如下所示:

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}`);
  }
);

如果这是它正在做的事情,我想这是合理的行为,因为空键不太可能是有效的.更内部"的错误可能会通过 observable 报告,并且应该由您传递给 subscribe 的错误回调处理.

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.

这篇关于使用combineLatest时如何从链接的rxjs observables中捕获错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆