js-async-handler
v1.0.0
Published
A lightweight async handler utility for Express.js middleware that automatically catches errors and passes them to the next middleware
Maintainers
Readme
js-async-handler
A lightweight async handler utility for Express.js middleware that automatically catches errors and passes them to the next middleware in the chain.
Features
- 🚀 Lightweight and fast
- 🔧 Works with both ES modules and CommonJS
- 💪 TypeScript support included
- 🛡️ Automatic error handling for async functions
- 📦 Zero dependencies
Installation
npm install js-async-handlerUsage
ES Modules
import { asyncHandler } from 'js-async-handler';
import express from 'express';
const app = express();
// Use with async route handlers
app.get('/users', asyncHandler(async (req, res) => {
const users = await User.findAll(); // This can throw an error
res.json(users);
}));
// Error will be automatically caught and passed to error middleware
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: 'Internal Server Error' });
});CommonJS
const { asyncHandler } = require('js-async-handler');
const express = require('express');
const app = express();
app.get('/users', asyncHandler(async (req, res) => {
const users = await User.findAll();
res.json(users);
}));API
asyncHandler(fn)
Wraps an async function and automatically catches any errors, passing them to the Express error handler.
Parameters
fn(Function): An async function that takes(req, res, next)as parameters
Returns
- (Function): Express middleware function
Example
const getUserById = asyncHandler(async (req, res) => {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user);
});
app.get('/users/:id', getUserById);Why Use This?
Without asyncHandler, you need to manually catch errors in every async route:
// Without asyncHandler - repetitive try/catch
app.get('/users', async (req, res, next) => {
try {
const users = await User.findAll();
res.json(users);
} catch (error) {
next(error);
}
});With asyncHandler, errors are automatically handled:
// With asyncHandler - clean and simple
app.get('/users', asyncHandler(async (req, res) => {
const users = await User.findAll();
res.json(users);
}));TypeScript
This package includes TypeScript declarations. No need to install additional @types packages.
import { asyncHandler } from 'js-async-handler';
import { Request, Response } from 'express';
const getUsers = asyncHandler(async (req: Request, res: Response) => {
const users = await User.findAll();
res.json(users);
});License
ISC
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
