Golo Roden
Golo Roden

Reputation: 150624

How to check for a specific exception in JavaScript?

I am writing a Node.js application, and inside one of its code blocks various exceptions may be thrown (by 3rd party code I call). Now I want to react on these exceptions, hence I do:

try {
  // Call 3rd party code
} catch (e) {
  // Handle e
}

Basically, this works fine, but ... how do I differ between different exceptions?

They all unfortunately have Error as constructor, hence this is no viable way. I may use the message property, but of course this is not the nicest way (as I am dependent on the fact the the message will never change, which is - IMHO - more probable than that the constructor changes).

Any ideas?

PS: Concretely - I need to react on SSL error while trying to do a tls.connect. How do I detect that it's an SSL error?

Upvotes: 2

Views: 1583

Answers (2)

Nick Mitchinson
Nick Mitchinson

Reputation: 5480

I would not recommend using a try/catch structure in Node, as I don't think it will work due to the asynchronous nature of Node (unless you're using basic, synchronous code).

Assuming you're utilizing asynchronous functions/packages, you'll probably have more luck checking the err status in a callback function.

Upvotes: 0

Peter Lyons
Peter Lyons

Reputation: 146034

Most errors that are system-level errors wrapped into javascript error objects will have a code property and errno you can compare against. The list is defined in uv.h in the node.js source code. That's probably your 2nd choice, with preference being

  1. instanceof where possible
  2. code or errno
  3. message

But the fact is sometimes you just have to look at message. Given the dynamic and loose typing of javascript and the fact that exceptions in general don't play a big role in node.js, there will be cases where checking the message is the best you can do.

Upvotes: 2

Related Questions