Angular 4, custom ErrorHandler doesn't recognize custom Error

I tried to create a custom global ErrorHandler and followed the instruction detailed here

application-error-handler (just the important parts)

@Injectable()
export class ApplicationErrorHandler extends ErrorHandler {

    constructor(private injector: Injector) {
        super(false);
    }

    handleError(error: any): void {

        if (error instanceof ApplicationError || error.originalError instanceof ApplicationError) {
            this.addError(error.originalError);
        }
        else {
            super.handleError(error);
        }
    }

app-module

 providers: [
    {
        provide: ErrorHandler,
        useClass: ApplicationErrorHandler
    }
],

app.component (only the important part)

public ngOnInit(): void { 
    const error = new ApplicationError();
    error.message = "fehler";
    throw error;
} 

application-error

export class ApplicationError implements Error {
    name: string;
    message: string;
    httpStatus?: number = 404;
    applicationStatus?: number;
    errorMessageTranslationkey: string;
    handled: boolean = false;
}

in my app.component I throw an ApplicationError (in ngOnInit), my ErrorHandler gets called successfully.
But my error in handleError is always of type Error and error.originalError is always undefined no matter if I throw my custom error and there the if will never resolve to true.

I have no idea why and how this happens.
What I see is that the error gets, so I assume, wrapped because when I debug I see error: Error: [object: Object] at viewWrappedDebugError (vendor.bundle.js)

Any idea what might cause this issue and how I can resolve it?

EDIT
As suspected it has something to do with Debugmode. As soon as I enable prodmode with enableProdMode(); it works as expected.

Still this doesn’t really answer my question yet.

How can I handle my custom error in angular’s debug mode?

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

You encounter this problem because ApplicationError is not an Error. You can use the following code in order to create a custom error: export class ApplicationError extends Error { httpStatus?: number = 404; applicationStatus?: number; errorMessageTranslationkey: string; handled: boolean = false; constructor(message?: string) { super(message); this.name = ApplicationError.name; Object.setPrototypeOf(this, ApplicationError.prototype); } } Related to the topic of creating a custom error, check also these links in order to have a full idea on the subject: extending Error, Array, Map in TypeScript referenced here Error – Custom Error Types section Why this needs to be an instance of Error? Because your… Read more »