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;
}
You can see how unwrapping is done in Angular itself: angular/modules/@angular/core/src/error_handler.ts, however they don't seem to handle rejection
(which is quite usefull) in any way so i use the following before unwrapping:
if(error.hasOwnProperty('rejection'))
{
error = error.rejection;
}
UncaughtPromiseError interface in zone.js.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With