Global Error Handler

Hi,
I’m trying to implement a global ErrorHandler but it gets called randomly, sometimes it goes ok but others an “Uncaught HttpErrorResponse {headers: HttpHeaders, status: 401…” is shown in the console (fired from polyfills.js:3) and the error never reaches the ErrorHandler.

Any idea of what is going on?

Thanks!

This is the ErrorHandler:

import { HttpErrorResponse } from ‘@angular/common/http’;
import { ErrorHandler, Injectable, Injector } from ‘@angular/core’;
import { App, IonicErrorHandler, NavController, ToastController } from ‘ionic-angular’;
import { LoginPage } from ‘…/…/…/features/login/login’;

@Injectable()
export class ErrorsHandler extends IonicErrorHandler implements ErrorHandler {
constructor(
private injector: Injector,
protected app: App,
private toastCtrl: ToastController,
) {
super();
}

handleError(error: Error | HttpErrorResponse) {
const navCtrl: NavController = this.app.getRootNav();
// If the error is IPromiseError, the error is inside rejection
if (error[‘rejection’]) { error = error[‘rejection’]; };

if (!navigator.onLine) {
  // No Internet connection
  // Handle offline error
  let toast = this.toastCtrl.create({
    message: `SIN CONEXIÓN A INTERNET`,
    duration: 10000,
    position: 'top',
    cssClass: 'warn-toast',
    showCloseButton: true,
    closeButtonText: 'cerrar',
  });

  toast.present();
}

if (error instanceof HttpErrorResponse) {
  // Server or connection error happened
  if (!navigator.onLine) {
    // Handle offline error
    let toast = this.toastCtrl.create({
      message: `SIN CONEXIÓN A INTERNET`,
      duration: 10000,
      position: 'top',
      cssClass: 'warn-toast',
      showCloseButton: true,
      closeButtonText: 'cerrar',
    });

    toast.present();
  } else {
    // Handle Http Error (error.status === 403, 404...)
    if (error.status === 401) {
      // And show notification to the user
      let toast = this.toastCtrl.create({
        message: `USUARIO NO AUTENTICADO ${error.status}. POR FAVOR, INTRODUZCA USUARIO Y CONTRASEÑA.`,
        duration: 10000,
        position: 'top',
        cssClass: 'warn-toast',
        showCloseButton: true,
        closeButtonText: 'cerrar',
      });

      toast.present();

      navCtrl.setRoot(LoginPage);
    } else {
      let toast = this.toastCtrl.create({
        message: `SE PRODUJO UN ERROR: ${error.status}. DISCULPE LAS MOLESTIAS.`,
        duration: 10000,
        position: 'top',
        cssClass: 'error-toast',
        showCloseButton: true,
        closeButtonText: 'cerrar',
      });

      toast.present();
    }
  }
}

// Log the error anyway
console.error(error);

}
}