Angular 9: instance of error not working with custom error handler

I am trying to implement custom error handling using the ErrorHandler class in angular

My Globalerror service looks like this

export class CustomErrors extends Error {
  button?: any;
  errObject: any;
  constructor() {
    super('custom');
    Object.setPrototypeOf(this, CustomErrors.prototype);
  }
}
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  // constructor(private injector: Injector) {}
  constructor() {}

  handleError(error: any) {
   
    console.log('custom error', error instanceof CustomErrors);

   }
}

In the component, I’m testing

ngOnInit() {
    try {
        throw new Error('error on do the thing');
    }
    catch (err) {
        const errs = new CustomErrors();
         //console.log('in service', errs instanceof CustomErrors);
          errs.button = 'Back to the start';
          throw err;
    }
}

but the console message in the handlerror function console.log('custom error', error instanceof CustomErrors); always throws false

I am not sure why it’s not getting true

12 thoughts on “Angular 9: instance of error not working with custom error handler”

  1. This is a known issue with TypeScript
    https://github.com/microsoft/TypeScript/issues/13965

    As a workaround try adding a type on your custom errors like this:

    export class CustomErrors extends Error {
      button?: any;
      readonly type: string = "CustomError";
      errObject: any;
      get type(): string {
         return "CustomError";
      }
      constructor() {
        super('custom');
        Object.setPrototypeOf(this, CustomErrors.prototype);
      }
    }
    

    You can even enforce the type member with an interface:

    export interface AppError {
        type: string;
    }
    

    and have all of your custom error classes implement it.

    Then you can replace instanceof with a check for error.type

    Reply

Leave a Comment