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?
You encounter this problem because
ApplicationError
is not anError
.You can use the following code in order to create a custom error:
Related to the topic of creating a custom error, check also these links in order to have a full idea on the subject:
Why this needs to be an instance of Error? Because your error pass through the following method:
Code available at
errors.ts
.Therefore if you are not throwing an
Error
instance, then a new instance is created.Intercepting uncatched promises in ErrorHandler
Another error case is when you return a promise which becomes rejected, from your method that is called by the Angular lifecycle (eg: handler, lifecycle-hook).
Therefore the error handling code can look like: