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?