While going through the Angular tutorial and converting it to my purposes, I decided that I want to combine the 2 varieties of error handler method shown into one, because i like the function of both.
This is all in one service, and these are the 2 methods from the tutorial:
private handleError1(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred', error.error.message);
} else {
console.error(`Backend error code ${error.status}`,
`body: ${error.error}`);
}
return throwError('Something bad happened');
}
which is called like this, where Group is my class from the REST server:
getGroups(): Observable<Group[]> {
return this.httpClient.get<Group[]>(`${this.restUrl}/group`).pipe(
tap(_ => this.log(`fetched groups`)),
catchError(this.handleError1)
);
}
and then alternatively, there is:
private handleError2<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.error(`${operation} failed!`, error);
return of(result as T);
}
}
which is called like this:
getGroups(): Observable<Group[]> {
return this.httpClient.get<Group[]>(`${this.restUrl}/group`).pipe(
tap(_ => this.log(`fetched groups`)),
catchError(this.handleError2<Group[]>('getGroups', []))
);
}
So I naively put together my combination error handler:
private handleError<T>(error: HttpErrorResponse,
operation = 'operation', result?: T) {
....
but I am having problems because I can't figure out how to parameterise it within catchError(). That HttpErrorResponse is obviously implied somehow when it's the only parameter, but how?