在需要进行错误处理的Angular应用里,从rxjs里导入catchError:
import { catchError, map, tap } from 'rxjs/operators';
getHeroes(): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
catchError(this.handleError<Hero[]>('getHeroes', []))
);
}
The catchError() operator intercepts an Observable that failed. It passes the error an error handler that can do what it wants with the error.
catchError这个操作符可以拦截发生错误的Observable, 将其传递给应用程序指定的错误处理方法去。
handleError的方法实现:
/**
* Handle Http operation that failed.
* Let the app continue.
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
this.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
要获取更多Jerry的原创文章,请关注公众号"汪子熙":