2

I am trying to implement a custom error handler for my angular application and I am stuck. It work but only on some really strange conditions.

Here is the stackblitz with the implementation: https://stackblitz.com/edit/angular-mqvzba

Here, in the project, we have a global-error-handler.service.ts inside the "app" folder and the hello.component.ts file with the other component files.

I already added the handling directive on the providers section of the app.module.ts. The strange thing is that if I test the newly created error before throwing it is indeed true that it is a instanceof CustomError.

What I am expecting to have is the result when the setTimeout is uncommented, but without using it.

Files to look at: - src/app/global-error-handler.service.ts - src/app/app.module.ts - src/app/hello.component.ts

Igor
  • 804
  • 10
  • 23

1 Answers1

2

Make sure your CustomError class extends the builtin Error class. Additionally, you will need to set the object prototype for instanceof to work properly when extending builtins. Reference: Custom error class in TypeScript

export class CustomError extends Error {    
    button?: any
    errObject: any    
    constructor() {        
        super('custom');
        Object.setPrototypeOf(this, CustomError.prototype);
    }
}

Should give you

Error received:  error on do the thing
global-error-handler.service.ts:42 My error! Yay!

Hope this helps!

kozan
  • 94
  • 5
  • It works on my example. Thanks. But not in my application, guess now I have to dig deeper. – Igor Jan 29 '20 at 16:37