I am currently working on an Angular 12 application and I have a requirement to implement a custom ErrorHandler for handling errors globally.
When I receive an error notification from the backend, I subscribe to it in the ToolService using this.notificationService.registerToServerCalls(......). Then, I raise a CustomException which is supposed to be handled by the CustomErrorHandler. However, when the CustomException is thrown, the code does not flow to the CustomErrorHandler.
tool.service.ts
@Injectable()
export class ToolService {
constructor(
private notificationService: NotificationService,
@Inject(ErrorHandler) private errorHandler: CustomErrorHandler) {
this.errorHandler.onUnhandledException$.subscribe({
next: (error: ErrorDetail[]) => {
this.dialogService.open(error);
}
});
}
this.notificationRService.registerToServerCalls<ErrorDetail[]>('Error', (errorDetail: ErrorDetail[]) => {
this.onError.next(errorDetail);
throw new CustomException(errorDetail);
});
notification.service.ts
public registerToServerCalls<T>(clientMethod: string, callback: (data: T) => void): void {
this.hubConnection.on(clientMethod, callback);
}
custom-exception.model.ts
export class CustomException extends Error {
error: ErrorDetail[];
constructor(error?: ErrorDetail[]) {
super();
this.error = error;
}
}
custom-error-handler.ts
@Injectable()
export class CustomErrorHandler implements ErrorHandler {
private onUnhandledException = new Subject();
onUnhandledException$ = this.onUnhandledException.asObservable();
isErrorHandled = false;
/**
* Override the base class error handler to handle the error.
*/
handleError(errorObj) {
if (this.isErrorHandled) {
return;
}
errorObj = errorObj.rejection ? errorObj.rejection : errorObj; // .rejection is required in case of promise rejections.
let errorDetails: ErrorDetail[];
errorDetails = errorObj.error;
this.onUnhandledException.next(errorDetails);
this.isErrorHandled = true;
}
}