2

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!

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. I moved the 401 and 403 into an http interceptor. I still want to send an email there for all the typescript erros (Just in case). Also I added error handling in my subscribe for so there won't be any loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.