RxJS HTTP请求错误处理

时间:2018-03-22 12:01:45

标签: error-handling rxjs

在我的项目中,我使用RxJS来处理HTTP请求。关于错误处理部分,我对此感到困惑:

    .switchMap((evt: any) => {
      return http.getComments(evt.params)
        .map(data => ({ loading: false, data }))
        .catch(() => {
          console.log('debugging here');
          return Observable.empty();
        });
    })

在上面的代码中,在switchMap运算符中,我使用http.getComments函数发送请求,我自己定义如下:

  getComments(params) {
    return Observable.fromPromise(
      this.io.get(path, { params })
    );
  }

在这个函数中,我使用fromPromise运算符将返回的Promise转换为observable。

问题是当HTTP请求失败时,catch内的switchMap运算符无法工作,调试控制台无法输出。那么我的代码有什么问题。

2 个答案:

答案 0 :(得分:1)

你真的需要抓住switchMap内的错误吗?如果需要,您可以在源代码中处理错误。

.switchMap((evt: any) => 
    http.getComments(evt.params).map(data => ({ loading: false, data }))
})
.subscribe(console.log, console.error);

任何方式,您的源代码看起来都没有任何错误,也许您的承诺在http失败时没有被拒绝,只是因为错误作为回应而解决(这是猜测,因为我已经看过了那之前)

答案 1 :(得分:0)

您的代码应该有效。这是一个简化的模拟,其中http调用由引发错误的函数代替。

f<-function(df,list_rows)
     {
       return(df[unlist(list_rows[df[1,1]]),])
     }

    lapply(list_data,f,list_rows=list_rows)
    [[1]]
      ID Name1 Name2 Name3 Name4
    1  1     3     4     6     8
    4  1     2     5     7     9

    [[2]]
      ID Name4 Name2 Name3 Name1
    1  2     7     3     2     1

    [[3]]
      ID Name3 Name1 Name4 Name2
    1  3     6     2     3     2
    3  3     6     2     3     2
    6  3     6     2     3     2

    [[4]]
      ID Name2 Name3 Name1 Name4
    2  4     7     1     1     3
    3  4     7     1     9     3
相关问题