首页 > 解决方案 > 确定错误属于可观察对象列表的可观察对象

问题描述

const obs1$ = this.service.getAllSources();
const obs2$ = this.service.getWidgetById(1);

combineLatest([obs1$, obs2$])
   .subscribe(pair => {
      const sources = pair[0];
      const widget = pair[1];
      // do stuff
   }, err => {
       // err can be from first or second observable, but which?    
       if (err.status === 404) {
          // here I need to know for which observable the error is ocurred ?!?!
          this.utilsService.alert('Widget with id 1 not found');
       }
       
       if (err.status === 500) {
          // here, I need to know from which observable occured
       }
   });

从后端我从不发送一个404 status来获取列表,所以,在这种情况下,我可以确定404它只来自第二个 observable。但是如果我想在error方法内部有另一个逻辑,我需要知道它是从哪个 observable 发生的。我怎么能这样做?谢谢

标签: angulartypescripterror-handlingrxjsobservable

解决方案


您可以将每个可观察catchError对象分别包装并处理它们:

combineLatest([
obs1$.pipe(catchError(e => ...)), 
obs2$.pipe(catchError(e => ...)),
]).subscribe(...)

或者您可以标记错误并在subscribe. 喜欢

obs1$.pipe(catchError(e => throwError({originalError: e, source: 'whatever you want'}))), 

推荐阅读