In my Angular 2 app I have a resolve guard which tries a xhr and throws a custom error if it fails:
return this.service.getProduct (id)
.catch (err => Observable.throw(new MyError(err.message, route, 500, err)));
MyError
is just an extension of Error
:
export class MyError extends Error {
constructor(message, routeSnapshot, code, err) {
super(message);
this.name = 'MyError';
this.routeSnapshot = routeSnapshot;
this.code = code;
this.err = err;
}
}
My global error handler receives an instance of ZoneAwareError
instead of MyError
:
export class MyErrorHandler implements ErrorHandler {
handleError(error) {
console.log('handling err', error);
// this prints a ZoneAwareError on the console
}
}
Is error
really supposed to be wrapped in ZoneAwareError
? How do I unwrap it to get MyError
back? Is it safe to rely on the error.rejection
property? (Because I can see MyError
there).
=== Edit:
Ok, I just discovered that Angular wraps errors in different sub-types of Error
, not only ZoneAwareError
. So far I have this function to unwrap them, but it feels a bit hacky:
function unwrap (err) {
let res = err.rejection ? err.rejection : err;
while (res.originalError) {
res = res.originalError;
}
res.name = res.name || 'unknown';
return res;
}