I'm writing a Restify application on Node.js. And I need to have a function that is called when some errors inside Restify callbacks are happening. This function should send a response to a client. If I'm not using Promises or async functions, I can do something like that:
server.on('uncaughtException', (req, res, route, err) => {
log.error(err);
res.send(err);
});
But if my callback is async function, then the exception inside a function isn't called, and unhandledPromiseRejection is raised instead.
How can I refactor my code so it would handle unhandled Promise rejections the same way it handles usual errors?
And yes, I know that I can check for errors inside a Restify middleware itself, but still it makes the code more complicated, it's easier to write
if (!core.validateUUID(req.params.deviceId)) {
throw new Error(`Device ${req.params.deviceId} is wrong`)
}
then
if (!core.validateUUID(req.params.deviceId)) {
return next(new restify.InvalidArgumentError({ body: {
success: false,
error: `Device ${req.params.deviceId} is wrong`,
} }));
}
via serge1peshcoff
No comments:
Post a Comment