Silent Node.js Crashes: Fixing Unhandled Rejections in Express

This is one of the most common ways Node.js applications crash silently in production: ```js // Unhandled rejection — will crash your app app.get('/users', async (req, res) => { const users = await User.find(); res.json(users); }); ``` If User.find() throws, there's no catch. In newer Node.js versions, it crashes the process. Two ways to fix this cleanly: Option 1 — try/catch: ```js app.get('/users', async (req, res) => { try { const users = await User.find(); res.json(users); } catch (error) { res.status(500).json({ message: 'Server error' }); } }); ``` Option 2 — Wrapper utility (cleaner at scale): ```js const asyncHandler = fn => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next); ``` Option 2 keeps your routes clean and error handling centralized. Production-ready code always handles failures gracefully. #NodeJS #JavaScript #BackendDevelopment #ExpressJS

To view or add a comment, sign in

Explore content categories