首頁>技術>

在需要進行錯誤處理的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); };}

27
最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • 幾項措施,讓你的api不再裸奔