I use custom errors (es6-error) allowing me to handle errors based on their class like so:
import { DatabaseEntryNotFoundError, NotAllowedError } from 'customError';
function fooRoute(req, res) {
doSomethingAsync()
.then(() => {
// on resolve / success
return res.send(200);
})
.catch((error) => {
// on reject / failure
if (error instanceof DatabaseEntryNotFoundError) {
return res.send(404);
} else if (error instanceof NotAllowedError) {
return res.send(400);
}
log('Failed to do something async with an unspecified error: ', error);
return res.send(500);
};
}
Now I'd rather use a switch for this type of flow, resulting in something like:
import { DatabaseEntryNotFoundError, NotAllowedError } from 'customError';
function fooRoute(req, res) {
doSomethingAsync()
.then(() => {
// on resolve / success
return res.send(200);
})
.catch((error) => {
// on reject / failure
switch (error instanceof) {
case NotAllowedError:
return res.send(400);
case DatabaseEntryNotFoundError:
return res.send(404);
default:
log('Failed to do something async with an unspecified error: ', error);
return res.send(500);
}
});
}
instanceof doesn't work like that however. So the latter fails.
Is there any way to check an instance for its class in a switch statement?