Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 326
KarolDepka Avatar asked Apr 26 '17 19:04

KarolDepka


People also ask

What are exceptions in TypeScript?

The try catch in TypeScript statement provides a way to handle some or all of the errors that may occur in an application. These errors are often referred to as an exception. In a try-catch statement, you code a try block that contains the statements that may throw an exception.

Can you throw custom exception with error object?

While the majority of exceptions are implementations of the global Error class, any old object can be thrown. With this in mind, there are two ways to throw an exception: directly via an Error object, and through a custom object.

What are the best practice of error handling in JS?

1. Don't Overuse the “Try-Catch” The first best practice of “Exception Handling” is, don't overuse “Exception Handling.” Typically, we handle exceptions at the outer layers and throws from the inner so that once an exception occurs, we can better understand what leads to it.


1 Answers

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.

like image 157
Nitzan Tomer Avatar answered Oct 05 '22 06:10

Nitzan Tomer