DEV Community

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

Posted on

13 6

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?

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, weโ€™ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, weโ€™ll see how we can identify what makes our TTFB high so we can fix it.

Read more

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.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay