While following Angular's tour of hero tutorial, I noticed that the author implemented an error handler for the http service (hero-service). What struck me was the use of 'any' as the type for the error argument in the handler, whereas in other Angular documentation related to the http client, the error handler type is always specified as 'HttpErrorResponse'.
If you're interested, here's the error handler code from the tour of heroes tutorial: 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);
};
}
Furthermore, take a look at the error handler example provided in Angular's HttpClient documentation 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.');
};
The discrepancy between using 'any' and 'HttpErrorResponse' as the error argument type made me wonder about best practices. When should an error argument be loosely typed, like 'any', and when should it be more specific?
Lastly, what would be the difference between defining the 'handleError' function without specifying the error type:
handleError(error){
}
And explicitly declaring the error parameter as type 'Any'?
handleError(error: Any){
}