Assuming node.js LTS and use of async await, what is the proper way to break execution? I'll display a promisified version and an async / await version to demonstrate the issue -
In the async / await version if an error is thrown from checkUserRouteRequirements
for example and 403
is sent back from the API express continues code execution and tries to res.json(result);
as well.
I would rather have the .catch
be in the validateRoute
method for re-usability since there are possibly hundreds of routes, and of course not have the error for trying to send headers twice.
Async / Await
router.get('/', async (req, res, next) => {
await validateRoute(roles.Approved, req, res, next);
// await does not break code execution
const result = await channelsService.getAll();
return res.json(result);
});
async function validateRoute(role, req, res, next) {
return checkUserRouteRequirements(req.user.sub, role).catch(error => {
res.status(403).json({});
});
}
Promisified
router.get('/', (req, res, next) => {
validateRoute(roles.Approved, req, res, next).then(() => {
channelsService.getAll().then(result => { return res.json(result) });
});
});
function validateRoute(role, req, res, next) {
return checkUserRouteRequirements(req.user.sub, role).catch(error => {
res.status(403).json({});
});
}
I am not a fan of putting try / catches everywhere either and throwing errors that have to be caught.
Any suggestions appreciated!