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?
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.
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.
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.
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.
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