且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular应用里HTTP请求的错误处理

更新时间:2022-09-09 16:34:38

在需要进行错误处理的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', []))
        );
    }

Angular应用里HTTP请求的错误处理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);
  };
}

Angular应用里HTTP请求的错误处理