Error handling RxJS HTTP请求错误处理

Error handling RxJS HTTP请求错误处理,error-handling,rxjs,Error Handling,Rxjs,在我的项目中,我使用RxJS来处理HTTP请求。关于错误处理部分,我遇到了如下困惑: .switchMap((evt: any) => { return http.getComments(evt.params) .map(data => ({ loading: false, data })) .catch(() => { console.log('debugging here'); re

在我的项目中,我使用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函数发送请求,我自己定义如下:

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


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

您的代码应该可以工作。这里是一个简化的模拟,其中http调用被引发错误的函数替换

import {Observable} from 'rxjs';


function getComments(params) {
    return Observable.throw(params);
}

const params = 'abc'; 

Observable.of(null)
.switchMap(_ => {
    return getComments(params)
      .map(data => ({ loading: false, data }))
      .catch(err => {
        console.log('debugging here', err);
        return Observable.empty();
    });
})
.subscribe(
    console.log,
    error => console.error('This method is not called since the error is already caught', error),
    () => console.log('DONE')
)

您真的需要捕获switchMap中的错误吗?如果需要,可以在源代码中处理错误

.switchMap((evt: any) => 
    http.getComments(evt.params).map(data => ({ loading: false, data }))
})
.subscribe(console.log, console.error);
无论如何,您的源代码看起来没有任何错误,可能您的承诺在http失败时没有被拒绝,只是用一个错误作为响应来解决。这是一个猜测,因为我以前看到过,为什么catch不能在switchMap中工作?
.switchMap((evt: any) => 
    http.getComments(evt.params).map(data => ({ loading: false, data }))
})
.subscribe(console.log, console.error);