Errors in Express
Sync
Async
app.get("/", async (req, res) => {
throw new Error("non async");
}app.get("/", async (req, res, next) => {
next(new Error("non async"));
}Async Solutions
app.get('*', wrapAsync(async (req, res) => {
await new Promise(resolve => setTimeout(() => resolve(), 50));
// Async error!
throw new Error('woops');
}));
app.use(function(error, req, res, next) {
// Gets called because of `wrapAsync()`
res.json({ message: error.message });
});
function wrapAsync(fn) {
return function(req, res, next) {
// Make sure to .catch() any errors and pass them along to the `next()` middleware in the chain, in this case the error handler.
fn(req, res, next).catch(next);
};
}Error Handler
Edge Case
Last updated