Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to check for a specific exception in JavaScript?

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?

Problem courtesy of: Golo Roden


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.

Solution courtesy of: Peter Lyons


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to check for a specific exception in JavaScript?


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription