Imagine having a route set up like this:
app.get('/malfunction', (req, res) => {
throw new Error('Malfunctioning!');
});
In this case, no response will be sent to clients.
However, you can include a middleware for handling all errors:
const errorMiddleware = (error, req, res, next) => {
if (error) {
console.error(error);
return res.status(500)
.json({
message: 'Internal server error',
});
}
next(error);
};
Yet, this approach won't work for async
routes, as they don't directly throw
.
For instance, consider the following scenario:
app.get('/malfunction', async (req, res) => {
throw new Error('Malfunctioning!');
});
To address this issue, you may create a wrapper like so:
const asyncRoute = f => (req, res, next) => {
return Promise.resolve(f(req, res, next)).catch(next);
};
app.get('/malfunction', asyncRoute(async (req, res) => {
throw new Error('Malfunctioning!');
}));
But it can become cumbersome as you now have to use this function for each route!
Is there a more efficient way to handle this situation?
- The solution provided in this Stack Overflow post aligns with the method I described above.
- On the other hand, the answer found in this Stack Overflow thread does not utilize
await
.