【问题标题】:rxjs Observable.catch() not workingrxjs Observable.catch() 不工作
【发布时间】:2017-05-22 22:36:04
【问题描述】:

我遇到了一个正在杀死我的应用程序的异常,我似乎无法 catch() / 使用它。我对此很陌生,所以我可能对catch 做错了什么?

private callConfigService(): Observable<Map<string,string>> {

    try {
        let confObs = this.contentService.fetchContentUsingGET(id, store, locale, null, false)
            .catch((res) => {
                console.log('Retrieving config FAILED! ', res);    // not hit
                return Observable.from([new Map<string,string>()]);
            }
        ).subscribe(
            (res) => { console.log('fetchContentUsingGET : ', res); },  // not worried about success scenario
            (err) => { console.log('error response: ', err); }  // not hit
         );  
    } catch (exception) {
        console.log('???', exception);  // not hit
    } finally {
        console.log('?????');   // hit
    }
    return Observable.of(new Map<string,string>()); // not hit
}

不幸的是,fetchConfigUsingGET 调用来自图书馆,所以我不确定里面有什么。但它看起来像一个热门的 observable,因为它产生了一个 404 异常,我什至没有调用 subscribe()

我不明白为什么 catch() 被完全跳过?

Uncaught * e {_body: "{"status":404,"error":"StatusCodeError","data":"404 - undefined"}", status: 404, ok: false, statusText: "Not Found", headers: t…}          bundle.umd.js:5

【问题讨论】:

  • 你真的在任何地方使用confObs吗?您看到的错误消息是什么?
  • 不,我根本不用,上面的声明就是它。这都是框架的一部分,很难获得一个独立的例子,但错误是:EXCEPTION: Response with status: 404 null for URL:
  • catch 在抛出异常时被调用。正如您所说,您无法判断 fetchConfigUsingGET 的行为是否与会引发 4xx http 状态代码异常的 http get 调用相同。只需订阅confObs,看看你会得到什么。
  • 执行失败的调用并打印 confObs 以确定如何使用它。让 confObs = this.configService.fetchConfigUsingGET(id, store, locale, null, false); console.log(confObs);
  • 更新了代码。即使使用 subscribe() 等,它也没有达到我的预期。我现在在控制台中看到了这个:Uncaught * e {_body: "{"status":404,"error":"StatusCodeError","data":"404 - undefined"}", status: 404, ok: false, statusText: "Not Found", headers: t…} 只是不知道如何catch() 那?

标签: angular rxjs reactive-programming rxjs5


【解决方案1】:

你试过了吗?在 subscrible 运算符中添加 OnError 处理程序。

let confObs = this.contentService.fetchContentUsingGET(id, store, locale, null, false)
                  .catch((res) => {
                      console.log('Retrieving config FAILED! ', res);
                      return Observable.from([new Map<string,string>()]);
                  })
                  .subscribe(
                      (res) => { console.log('fetchContentUsingGET : ', res);},
                      (err) => { console.log('fetchContentUsingGET.Error : ', err);},
                      () => { //on completed }
                  );

【讨论】:

  • 好电话。我最终在本地添加了这个,但不幸的是它没有帮助。我会用它更新上面的代码。
  • 如果是这种情况,那么 fetchContentUsingGET 中应该会发生异常而无需处理程序。你必须检查图书馆。
  • 如果fetchContentUsingGET() 抛出异常,那么我的catch() 将无法捕获它? (抱歉,rxjs 新手...)
  • 不,不是。未处理的异常必须在返回 Observable 对象之前发生。
  • 这很有意义。谢谢,我看看能不能了解fetchContentUsingGET() 的工作原理。
猜你喜欢
  • 2017-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-06
相关资源
最近更新 更多