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

时间:2022-07-23
本文章向大家介绍Angular应用里HTTP请求的错误处理,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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