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

1 Answer 1

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!

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

1 Comment

It works on my example. Thanks. But not in my application, guess now I have to dig deeper.

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.