DEV Community

Cover image for Switch-cased Error Handling in JavaScript
Chris Cook
Chris Cook

Posted on

Switch-cased Error Handling in JavaScript

I recently stumbled upon this interesting piece of code from one of Shopify libraries for Node.js. It makes use of an interesting way of error handling with a switch-case statement.

try {
  // ...
} catch (e) {
  switch (true) {
    case e instanceof Shopify.Errors.InvalidOAuthError:
      res.status(400);
      res.send(e.message);
      break;
    case e instanceof Shopify.Errors.CookieNotFound:
    case e instanceof Shopify.Errors.SessionNotFound:
      // This is likely because the OAuth session cookie expired before the merchant approved the request
      res.redirect(`/auth?shop=${req.query.shop}`);
      break;
    default:
      res.status(500);
      res.send(e.message);
      break;
  }
}
Enter fullscreen mode Exit fullscreen mode

shopify-app-node/server/middleware/auth.js

It's not necessarily shorter than its if-else ladder counterpart and in most cases only makes sense if you're dealing with a library built with various Error classes. Also the performance and readability aspects are up for debate. What do you think?

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

I use it all the time. You can also use it to test the conditions of anything you like. Often makes for more readable code

Collapse
 
zirkelc profile image
Chris Cook

I find it difficult to apply such patterns (especially e instaceof <class>) because in JS it's not obvious what the errors that you have to catch and handle could be. In other language such as C#, Java, etc. the thows signature gives you this information, but in JS you have to hope it's documented somewhere.