As I was working on customizing the Angular tutorial to fit my needs, I found myself wanting to merge the two error handler methods showcased in the tutorial into one. I appreciate the functionality of both methods and believe combining them will be beneficial for my project.
These two methods are within a single service and are demonstrated as follows:
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');
}
This method is invoked like this, with Group
representing 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)
);
}
Additionally, there is another error handling method presented:
private handleError2<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.error(`${operation} failed!`, error);
return of(result as T);
}
}
This method is called in the following manner:
getGroups(): Observable<Group[]> {
return this.httpClient.get<Group[]>(`${this.restUrl}/group`).pipe(
tap(_ => this.log(`fetched groups`)),
catchError(this.handleError2<Group[]>('getGroups', []))
);
}
In an attempt to combine these two error handler methods, I created the following merged version:
private handleError<T>(error: HttpErrorResponse,
operation = 'operation', result?: T) {
....
However, I am currently facing issues as I am unsure how to parameterize it within the catchError()
function. It seems that HttpErrorResponse
is implicitly defined when it is the only parameter, but I am struggling to grasp how to implement it effectively.