0
0
Expressframework~5 mins

Async middleware wrapper in Express

Choose your learning style9 modes available
Introduction

Async middleware wrapper helps handle errors in async Express middleware easily. It avoids repeating try-catch blocks.

When writing async route handlers in Express that use await.
When you want to catch errors from async functions and pass them to Express error handlers.
When you want cleaner code without many try-catch blocks in middleware.
When you want consistent error handling for async middleware.
When building APIs that use async database calls or external requests.
Syntax
Express
const asyncWrapper = (fn) => (req, res, next) => {
  Promise.resolve(fn(req, res, next)).catch(next);
};

This is a higher-order function that takes an async function fn and returns a new middleware function.

It runs fn and catches any errors, passing them to next() for Express error handling.

Examples
Basic async wrapper function that catches errors from async middleware.
Express
const asyncWrapper = (fn) => (req, res, next) => {
  Promise.resolve(fn(req, res, next)).catch(next);
};
Using asyncWrapper to wrap an async route handler that fetches data.
Express
app.get('/data', asyncWrapper(async (req, res) => {
  const data = await getDataFromDb();
  res.json(data);
}));
Async wrapper used for a POST route creating a user, handling errors automatically.
Express
app.post('/user', asyncWrapper(async (req, res) => {
  const user = await createUser(req.body);
  res.status(201).json(user);
}));
Sample Program

This Express app uses an async middleware wrapper to handle errors in an async route. The route /hello returns JSON after a delay. Errors are caught and sent as JSON error responses.

Express
import express from 'express';
const app = express();
app.use(express.json());

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

// Simulated async function
const getData = async () => {
  return new Promise((resolve) => setTimeout(() => resolve({ message: 'Hello World' }), 100));
};

app.get('/hello', asyncWrapper(async (req, res) => {
  const data = await getData();
  res.json(data);
}));

// Error handler middleware
app.use((err, req, res, next) => {
  res.status(500).json({ error: err.message });
});

app.listen(3000, () => console.log('Server running on port 3000'));
OutputSuccess
Important Notes

Always use the async wrapper on async middleware to avoid unhandled promise rejections.

The wrapper passes errors to Express's built-in error handler or your custom error middleware.

This pattern keeps your code clean and easier to read.

Summary

Async middleware wrapper catches errors from async functions automatically.

It helps avoid repetitive try-catch blocks in Express middleware.

Use it to keep async route handlers clean and error-safe.