识别错误属于可观察列表的哪个可观察对象
Identify of which observable the error belongs for a list of observables
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
仅来自第二个可观察对象。但是如果我想在 error
方法中有另一个逻辑,我需要知道它是从哪个 observable 发生的。我该怎么做?谢谢
您可以将每个 observable 包装在 catchError
中并分别处理它们:
combineLatest([
obs1$.pipe(catchError(e => ...)),
obs2$.pipe(catchError(e => ...)),
]).subscribe(...)
或者您可以标记错误并在 subscribe
中处理它们。好像
obs1$.pipe(catchError(e => throwError({originalError: e, source: 'whatever you want'}))),
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
仅来自第二个可观察对象。但是如果我想在 error
方法中有另一个逻辑,我需要知道它是从哪个 observable 发生的。我该怎么做?谢谢
您可以将每个 observable 包装在 catchError
中并分别处理它们:
combineLatest([
obs1$.pipe(catchError(e => ...)),
obs2$.pipe(catchError(e => ...)),
]).subscribe(...)
或者您可以标记错误并在 subscribe
中处理它们。好像
obs1$.pipe(catchError(e => throwError({originalError: e, source: 'whatever you want'}))),