我在Angular中使用过rxjs,并且我熟悉流中的catchError运算符的使用pipe,尤其是对于HttpClient(XHR)调用
我的问题是catchError手术如何进行?如何在后台捕捉错误?
https://www.learnrxjs.io/operators/error_handling/catch.html
import { throwError, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
//emit error
const source = throwError('This is an error!');
//gracefully handle error, returning observable with error message
const example = source.pipe(catchError(val => of(`I caught: ${val}`)));
//output: 'I caught: This is an error'
const subscribe = example.subscribe(val => console.log(val));
Run Code Online (Sandbox Code Playgroud)
更新:
使用“已接受答案”中的详细信息,我在StackBlitz TypeScript项目中对以下内容进行了测试。查看try / catch和subscriber.error的好例子:
import { throwError, of, Observable } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
const exampleOne$ = new Observable(subscriber => {
throw new Error('thrown');
});
exampleOne$.pipe(
catchError(val => of(`Exmaple One ${val}`))
).subscribe(console.log); // Exmaple One Error: thrown
const exampleTwo$ = new Observable(subscriber => {
try {
throw new Error('native error')
}
catch (e) {
subscriber.error(e);
}
});
exampleTwo$.pipe(
catchError(val => of(`Example Two ${val}`))
).subscribe(console.log); // Example Two Error: thrown
Run Code Online (Sandbox Code Playgroud)
该catchError运营商不直接赶上同样的方式,异常使用的是捕获错误的try/ catch声明。
在内部,它订阅应用了它的可观察源,并镜像源next和complete通知-即那些通知不更改地流经运算符。
但是,如果操作员收到error通知,它将错误传递给提供的回调,从而使操作员的调用者有机会处理该错误。
的error通知可以观察到的一个实现中通过调用用户的来实现error的方法,就像这样:
const source = new Observable<string>(subscriber => {
subscriber.error(new Error'Kaboom!'));
});
Run Code Online (Sandbox Code Playgroud)
在此,不会引发任何异常,并且不需要try/ catch。该错误会通过其方法传递给订阅者- catchError操作员订阅源,因此是订阅者error。
这就是throwError问题中使用的函数的实现方式。
的error通知,也可以通过抛出一个异常,这样的影响:
const source = new Observable<string>(subscriber => {
throw new Error('Kaboom!');
});
Run Code Online (Sandbox Code Playgroud)
在这里,try/ catch的实现中Observable.subscribe的/ 语句将捕获异常,并将通过调用订阅者的error方法将错误通知传递给订阅者。
捕捉引发的异常是Observable和操作符实现的责任。
无论在何处传递用户指定的函数(例如,在类似的运算符中)map,对这些函数的调用都包装在try/ catch语句中,任何捕获的异常都作为error订阅者的error方法通过通知传递给订阅者。
| 归档时间: |
|
| 查看次数: |
150 次 |
| 最近记录: |