angularangular-httpclientangular-errorhandler

Angular how to use HttpClient in custom ErrorHandler?


I would like to call my rest API in my custom error handler to email myself when the handler is called.

I have tried to use the Injector, but I get this error:

Error: Cannot instantiate cyclic dependency! HttpClient

Here you can see my error handler:

import { Router } from '@angular/router';
import { ErrorHandler, Injector, Injectable, NgZone } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class AppErrorHandler extends ErrorHandler {

  constructor(private injector: Injector) {
    super();
  }

  private get toastrService(): ToastrService {
    return this.injector.get(ToastrService);
  }

  private get http(): HttpClient {
    return this.injector.get(HttpClient);
  }

  private get router(): Router {
    return this.injector.get(Router);
  }

  private get ngZone(): NgZone {
    return this.injector.get(NgZone);
  }

  public handleError(error: any): void {
    if (error.status === 401) {
      this.ngZone.run(() => this.router.navigate(['/home']));
      this.toastrService.error('Login first', 'Error');
    } else if (error.status === 403) {
      this.ngZone.run(() => this.router.navigate(['/home']));
      this.toastrService.error('unauthorize', 'Error');
    } else {
      this.http.post<any>('/api/error-mailer', error).subscribe(() => { });
      this.toastrService.error('Something went wrong', 'Error', { onActivateTick: true });

    }

    super.handleError(error);
  }
}

I might also have the wrong aproach so if you could help me that be great!


Solution

  • You should handle httpClient errors with a http interceptor. In the interceptor you can inject the services you need. However you should keep an eye on calling a http request from the interceptor, cause it will run through the interceptor, and you can end up having a loop when your error-mailer is down.