CptDayDreamer
CptDayDreamer

Reputation: 1794

Angular override global ErrorHandler

We use a global error handler in our project. The problem is that we got a special case now that we would like to handle separately but we cannot. The global error handler is basically provided in the app.module.ts:

{ provide: ErrorHandler, useClass: GlobalErrorHandler },

We divide between the errors and then handle them with a service.

  handleError(error: any): void {
    const errorService = this.injector.get(ErrorService);
    const notifier = this.injector.get(NotificationService);

    let message: string;

    if (error instanceof HttpErrorResponse) {
      message = errorService.getServerErrorMessage(error);
      notifier.showError(message);
    } else if (error === undefined) {
      message = errorService.getServerErrorMessage(error);
      notifier.showError(message);
    } else if (error instanceof Observable) {
      message = this.translate.instant('ERROR.SERVER_NOT_REACHABLE');
      notifier.showError(message);
    } else {
      message = errorService.getClientErrorMessage(error);
      notifier.showError(message);
    }

    this.logger.error(message, `\n - Stacktrace: \n${error.stack}`);
  }

The problem now is that we know for some application that if status code 406 is returned for that special call it means that AWS couldn't recognize a face. We would like to return this translated message and try to add an if-clause after the subscribe() of the function that calls the backend API.

  (err) => {
    if (err.statusCode == 406) {
      this.notifier.showError(
        this.translate.instant(
          'APPLICATIONS.FACE_DETECTION.NOTIFICATION.FACE_ERROR'
        )
      );
    }
  }

Instead of achieving anything like this we just get the error message of the backend (that's the right behaviour because we tell to do this in the ErrorHandlerService but how to override or to tell that it should not care for that special call?

Upvotes: 0

Views: 1091

Answers (2)

Adnan
Adnan

Reputation: 994

Create a model for AWS response and in your first clause of your error handler check if that your http code is 406 and the http response has x props to make sure it's AWS response.

if (typeof e.error === 'object' && (e.error as 
AWSError)?.errorCode) {
      const awsError = e.error as AWSError;
}
...
console.log(awsError.errorMessage)

Upvotes: 1

Ben L
Ben L

Reputation: 744

Have you tried catching it in the pipe of the http request using catchError?

.pipe(
  catchError(err => {
     if (err instanceof HttpErrorResponse && err.status == 406) {
       // handle error
     }
  }).subscribe(res => ...)

Upvotes: 0

Related Questions