Async error handling helps catch problems in routes that use asynchronous code, so your app doesn't crash and can respond properly.
Async error handling in routes in Express
app.get('/route', async (req, res, next) => { try { // async code here res.send(result); } catch (error) { next(error); // pass error to Express error handler } });
Use try/catch inside async route handlers to catch errors.
Call next(error) to let Express handle the error properly.
app.get('/user/:id', async (req, res, next) => { try { const user = await getUserById(req.params.id); res.json(user); } catch (err) { next(err); } });
app.post('/data', async (req, res, next) => { try { const saved = await saveData(req.body); res.status(201).send(saved); } catch (error) { next(error); } });
This Express app has a route that fetches data asynchronously. If the ID is '0', it throws an error. The error is caught and passed to the error handler, which sends a 500 status with the error message.
import express from 'express'; const app = express(); app.use(express.json()); // Simulated async function that may throw async function fetchData(id) { if (id === '0') throw new Error('Invalid ID'); return { id, name: 'Item ' + id }; } app.get('/item/:id', async (req, res, next) => { try { const data = await fetchData(req.params.id); res.json(data); } catch (error) { next(error); } }); // Error handler middleware app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Always use next(error) in async routes to avoid unhandled promise rejections.
Express error handler middleware must have four parameters: (err, req, res, next).
Without proper async error handling, your server might crash or hang on errors.
Use try/catch blocks in async route handlers to catch errors.
Pass errors to Express with next(error) for centralized handling.
Set up an error handler middleware to send user-friendly error responses.