catchError 使用笔记
我一直以为source observable
即使发生错误之后, 也会按照pipe里面的operator 的顺序处理之后再进入catchError
, 其实不是的,是跳过前面的operator 处理,直接被catchError
operator catch 住。例子如下:
const example$ = new Subject<number>();
// 当source observable 发生错误,pipe 里面的operator 都不走了,直接走catachError
example$.pipe(
map(x => {
console.log(x); // 当source observable 发生错误之后,此句不会执行
return x + 1;
}),
catchError(error => {
console.log(error);
throw 'excute ' + error + ' failed';
})
).subscribe(
next => {
console.log('value=', next);
},
error => {
console.log('had error: ', error);
}
);
example$.next(1);
example$.error(2);
打印结果如下:
map 1
value= 2
catchError 2
had error: excute 2 failed