在Angular的英雄教程中,作者为http服务(hero-service)编写了一个错误处理程序。我很困惑为什么作者选择使错误处理程序的错误参数类型为任何,而在其他有关http客户端的Angular文档中,错误处理程序类型始终指定为httperrorresponse类型。
这里是英雄之旅教程中的错误处理程序:https://angular.io/tutorial/toh-pt6#error-handling
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的httpclient文档https://angular.io/guide/http#getting-error-details中提供的错误处理程序示例>
private handleError(error: HttpErrorResponse) { if (error.error instanceof ErrorEvent) { // A client-side or network error occurred. Handle it accordingly. console.error('An error occurred:', error.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, console.error( `Backend returned code ${error.status}, ` + `body was: ${error.error}`); } // return an observable with a user-facing error message return throwError( 'Something bad happened; please try again later.'); };
您可以看到这里的错误参数类型指定为HttpErrorResponse。错误参数什么时候应该键入,什么时候应该更具体?
同样,如果我只有handleError函数,请使用无类型的参数:
handleError(error){ }
与做其他事情有什么不同>>
handleError(error: Any){ }
在Angular的英雄教程中,作者为http服务(hero-service)编写了一个错误处理程序。我对作者为什么选择使错误处理程序的错误参数类型为任何形式感到困惑,...
RXJS中的错误始终是any
类型。链中的任何操作员都可能抛出任何类型的错误。因此,向下转换到HttpErrorResponse
有点不安全,但允许这样做。
如果只有每个人都将HttpClient直接连接到此错误处理程序,那将是安全的。但是,有人可以添加某种自定义运算符(也许找不到从响应缓存中获取的自定义运算符),并且该运算符可能引发其他错误。这将导致运行时异常。