I presume you're asking about something like Express middleware:
Middleware is not the appropriate place to deal with this type of error handling because middleware chains function calls rather than wraps them.
Instead one approach to use is to create a function named something like asAsync() and wrap the route handler with that. Example:
function asAsync(handler) {
return async (req, res, next) => {
try {
await handler(req, res, next);
next();
} catch (err) {
next(err);
}
}
}
app.get('/names', asAsync(async (req, res) => {
const names = await db.names.findAll();
});
An even nicer way, if you're using TypeScript, is to use decorators, exemplified by libraries like inversify-express-utils or NestJS. These frameworks use decorators to abstract away the repetitive code. A route handler in NestJS simply looks like this:
@Get('/names')
async get(req, res) {
return await db.names.findAll();
}