Simplifying Asynchronous Error Handling in Express.js with catchAsync
Photo by Pankaj Patel on Unsplash
Purpose:
catchAsync
handles asynchronous errors in Express.js routes by catching rejected promises and passing them to the error-handling middleware.
Key Concepts:
Higher-Order Function: Takes an async function and returns a new function that wraps it.
Error Handling: Automatically catches errors and calls
next(err)
to pass them to Express error handlers.
Code Explanation:
const catchAsync = (fn: RequestHandler) => {
return (req: Request, res: Response, next: NextFunction) => {
Promise.resolve(fn(req, res, next)).catch(err => next(err));
};
};
export default catchAsync;
Usage Example:
Instead of:
app.get('/example', async (req, res, next) => {
try {
// Async code
} catch (err) {
next(err);
}
});
Use catchAsync
:
app.get('/example', catchAsync(async (req, res, next) => {
// Async code
}));
Benefits:
Cleaner Code: Eliminates repetitive try-catch blocks.
Consistency: Uniform error handling.
Readability: More concise route handlers.