Home > other >  How to use `throw` properly in try...catch block when other unexpected errors might occur?
How to use `throw` properly in try...catch block when other unexpected errors might occur?

Time:07-28

The title may not be the best.

Code sample:

a = 1;
try {
   if (a == 1) {
      throw ('My fake error.');
   }
} catch (err) {
   console.log(err.message);
}

Assume I have more complex code in the try block. If a statement in that try block throws an error I can get the text of the error by looking at err.message. But, if I throw an error myself I can only see the text if I look at err because err.message is undefined.

How do I catch both unexpected errors, and errors I throw in the same catch block without writing more complex code to see if err.message is null for instance? I would expect both to return a similar structure, but they do not.

CodePudding user response:

A good approach to this sort of issue is to always throw Error objects, and not literals.

It is considered good practice to only throw the Error object itself or an object using the Error object as base objects for user-defined exceptions. The fundamental benefit of Error objects is that they automatically keep track of where they were built and originated.

If you throw a plain non-error value, that value will be the expression in the catch section - which will (probably) not have the .message (or .stack) property, and be less than useful as a result.

So, replace throw ('My fake error.'); with throw new Error('My fake error.'); - and then, in catch, doing console.log(err.message) may log either My fake error., or it may log whatever other unexpected error occurred, if the rest of the code around there is well structured enough to always throw Error objects. Just enabling and following that no-throw-literal ESLint rule referenced above would be sufficient.

  • Related