How to handle async errors in Node.js?

I’m building a Node.js REST API and struggling with proper error handling in async/await functions. When an async function throws an error inside an Express route handler, the server just crashes instead of returning a proper error response.

Here’s what I have:

app.get('/users/:id', async (req, res) => {
  const user = await User.findById(req.params.id);
  res.json(user);
});

What’s the best practice for handling errors in async Express routes?

Great question! The issue is that Express doesn’t natively handle async errors. You need to either wrap your handlers or use a helper.

Option 1: Try-catch wrapper

const asyncHandler = (fn) => (req, res, next) => {
  Promise.resolve(fn(req, res, next)).catch(next);
};

app.get('/users/:id', asyncHandler(async (req, res) => {
  const user = await User.findById(req.params.id);
  if (!user) throw new NotFoundError('User not found');
  res.json(user);
}));

Option 2: express-async-errors package
Just require it at the top of your app:

require('express-async-errors');

Then add a global error handler middleware:

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(err.status || 500).json({ error: err.message });
});

I’d recommend Option 2 for simplicity, but Option 1 gives you more control.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.