RxJS - 错误处理运算符 catchError
此运算符通过返回新的 Observable 或错误来捕获源 Observable 上的错误。
语法
catchError(selector_func: (err_func: any, caught: Observable) => O):Observable
参数
selector_funct − 选择器函数接受 2 个参数,错误函数和 caught,后者是 Observable。
返回值
它根据 selector_func 发出的值返回一个可观察对象。
示例
import { of } from 'rxjs';
import { map, filter, catchError } from 'rxjs/operators';
let all_nums = of(1, 6, 5, 10, 9, 20, 40);
let final_val = all_nums.pipe(
map(el => {
if (el === 10) {
throw new Error("Testing catchError.");
}
return el;
}),
catchError(err => {
console.error(err.message);
return of("From catchError");
})
);
final_val.subscribe(
x => console.log(x),
err => console.error(err),
() => console.log("Task Complete")
);
输出

