Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "unwrap" a ZoneAwareError?

Tags:

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;
}
like image 299
André Avatar asked Feb 03 '17 15:02

André


1 Answers

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.

like image 62
kemsky Avatar answered Sep 23 '22 10:09

kemsky