Error Handling in Node.js: A Reusable Pattern

Most Node.js apps don't crash because of bad code. They crash because of bad error handling. Here's a pattern I use in almost every project: Instead of letting unhandled promise rejections silently kill your server, wrap your async route handlers in a reusable utility: const asyncHandler = (fn) => (req, res, next) => { Promise.resolve(fn(req, res, next)).catch(next); }; app.get('/user/:id', asyncHandler(async (req, res) => { const user = await getUserById(req.params.id); if (!user) throw new AppError('User not found', 404); res.json(user); })); app.use((err, req, res, next) => { res.status(err.status || 500).json({ message: err.message || 'Internal Server Error', }); }); That's it. One wrapper, one central error middleware, and your entire app handles errors consistently. The key insight: errors should flow to one place, not be scattered across every route with try/catch blocks copy-pasted everywhere. A custom AppError class lets you attach HTTP status codes and meaningful messages, so your API responses stay predictable for frontend teams. This also makes logging much easier — you intercept everything in one middleware and send it to whatever logging service you use. Small pattern, big payoff. Your teammates will thank you, and your on-call rotations will get a lot quieter. What's the error handling pattern you swear by in your Node.js projects — do you use something similar, or have you found a better approach? #nodejs #backend #javascript #softwaredevelopment #webdevelopment

  • logo

To view or add a comment, sign in

Explore content categories