如何从RxJS映射运算符引发错误(角度) [英] How to throw error from RxJS map operator (angular)

查看:92
本文介绍了如何从RxJS映射运算符引发错误(角度)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据条件从可观察的 map 运算符中引发错误.例如,如果未收到正确的API数据.请查看以下代码:

I want to throw an error from my observable's map operator based on a condition. For instance if correct API data is not received. Please see the following code:

private userAuthenticate( email: string, password: string ) {
    return this.httpPost(`${this.baseApiUrl}/auth?format=json&provider=login`, {userName: email, password: password})
        .map( res => { 
            if ( res.bearerToken ) {
                return this.saveJwt(res.bearerToken); 
            } else {
                // THIS DOESN'T THROW ERROR --------------------
                return Observable.throw('Valid token not returned');
            }
        })
        .catch( err => Observable.throw(this.logError(err) )
        .finally( () => console.log("Authentication done.") );
}

基本上,如您在代码中看到的那样,如果响应(res对象)没有"bearerToken",我想抛出一个错误.因此,在我的订阅中,它进入了下面提到的第二个参数(handleError).

Basically as you can see in the code, if the response (res object) doesn't have 'bearerToken' i want to throw out an error. So that in my subscription it goes into the 2nd parameter (handleError) mentioned below.

.subscribe(success, handleError)

有什么建议吗?

推荐答案

只需将错误抛出在map()运算符内即可. RxJS中的所有回调都包裹有try-catch块,因此它将被捕获,然后作为error通知发送.

Just throw the error inside the map() operator. All callbacks in RxJS are wrapped with try-catch blocks so it'll be caught and then sent as an error notification.

这意味着您什么也不返回,只是抛出错误:

This means you don't return anything and just throw the error:

map(res => { 
  if (res.bearerToken) {
    return this.saveJwt(res.bearerToken); 
  } else {
    throw new Error('Valid token not returned');
  }
})

throwError()(在RxJS 5中为以前的Observable.throw())是一个Observable,仅发送error通知,但map()不在乎您返回的内容.即使您从map()返回一个Observable,它也将作为next通知传递.

The throwError() (former Observable.throw() in RxJS 5) is an Observable that just sends an error notification but map() doesn't care what you return. Even if you return an Observable from map() it'll be passed as next notification.

最后,您可能不需要使用.catchError()(RxJS 5中的以前的catch()).如果在发生错误时需要执行任何副作用,则最好使用tap(null, err => console.log(err))(在RxJS 5中为以前的do()).

Last thing, you probably don't need to use .catchError() (former catch() in RxJS 5). If you need to perform any side effects when an error happens it's better to use tap(null, err => console.log(err)) (former do() in RxJS 5) for example.

2019年1月:已针对RxJS 6更新

Jan 2019: Updated for RxJS 6

这篇关于如何从RxJS映射运算符引发错误(角度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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