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; } }
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)
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
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. thethows
signature gives you this information, but in JS you have to hope it's documented somewhere.