Switch-cased Error Handling in JavaScript

Chris Cook - May 6 '22 - - Dev Community

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?

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player