I have the following express controller
class ThingsController {
static async index(req, res, next) {
try {
const things = await Thing.all();
res.json(things);
} catch(err) {
next(err);
}
}
}
and router
router.route('/things').get(ThingsController.index)
In my app I plan to have several controllers which use promises to render the result
I do not want to repeat try/catch block every time
My first solution was to extract this logic into handle promise rejection function:
const handlePromiseRejection = (handler) =>
async (req, res, next) => {
try{
await handler(req, res, next);
} catch(err) {
next(err);
};
};
and now we can remove try/catch block from the ThingsController.index and need to change router to this:
router.route('/things')
.get(handlePromiseRejection(ThingsController.index))
But adding handlePromiseRejection
on every route might be tedious task and I would want to have more clever solution.
Do you have any ideas?