Back to library
🟢Node.jsjavascriptintermediate

Async Route Handler Wrapper

Wrapper to handle async errors in Express routes

expressasyncerror-handling

Code

1// Async handler wrapper
2const asyncHandler = (fn) => {
3  return (req, res, next) => {
4    Promise.resolve(fn(req, res, next)).catch(next);
5  };
6};
7
8// Usage example
9app.get('/api/users', asyncHandler(async (req, res) => {
10  const users = await User.find();
11  res.json(users);
12}));
13
14app.post('/api/users', asyncHandler(async (req, res) => {
15  const user = await User.create(req.body);
16  res.status(201).json(user);
17}));
18
19// With custom error
20app.get('/api/users/:id', asyncHandler(async (req, res) => {
21  const user = await User.findById(req.params.id);
22  
23  if (!user) {
24    throw new Error('User not found');
25  }
26  
27  res.json(user);
28}));

Quick Tips

  • Click the "Copy" button to copy the code to your clipboard
  • This code is production-ready and can be used in your projects
  • Check out related snippets below for more examples

Related Snippets

Build Your Own Snippet Library

Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.