After exploring the capabilities of https://angular.io/api/core/ErrorHandler, I have found that it allows me to override the global error handler with an error object. I appreciate how I can easily define my own global error handler and use it wherever necessary.
However, when working with RxJS, I find myself using
catchError(this.handleError(my, params, go, here))
frequently.
I wish to make my handleError()
method global and integrate it into my global error handler. Unfortunately, it seems that this may not be technically feasible.
My handleError
method is designed to log errors to a logger, console, and return a dummy Observable
for smooth execution in combination with RxJS's catchError
.
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
constructor(private messageService: MessageService) { }
public handleError<T>(
error: HttpErrorResponse, operation = 'operation', result?: T) {
var errorMessage = '';
if (error.error instanceof ProgressEvent) {
errorMessage = `Client error occurred: ${error.message}`;
} else {
errorMessage = `Adam's error ${error.status}: ${error.message}`;
}
console.error(errorMessage);
this.messageService.add(`${operation} failed: ${errorMessage}`);
return of(result as T);
}
}
Is there a way to implement this as a global error handler? Or would it be better to approach it differently? While creating an "error service" to manage my generic handleError()
and injecting it everywhere is a possibility, it does seem cumbersome.