简体   繁体   中英

Exception nesting/wrapping in TypeScript

Is it possible/common-practice to nest/wrap exception (cause) in TypeScript, like in Java?

try {
  // do something
} catch (e) {
  throw new MyException("Exception while doing something", e);
}

I mean it's probably not a problem to just have a custom ctor for MyException , to pass in the e arg as cause , but what about reporting (printing) the stack traces later on?

If you're looking for the stack trace then you can do this:

function normalizeError(e: any): Error {
    if (e instanceof Error) {
        return e;
    }

    return new Error(typeof e === "string" ? e : e.toString());
}

And then:

try {
    throw [1, "string", true];
}
catch (e) {
    e = normalizeError(e);
    console.log(e.stack);
}

Which will print something like:

Error: 1,string,true
at normalizeError (:5:12)
at :11:9

If you are targetting es6 then you can extend the Error class instead of having this normalizeError function, but if you can't target es6 then you should avoid extending native classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM