Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
// Pattern 1 – manual try/catch (always safe) app.get('/a', async (req, res, next) => { try { const data = await fetchData(); res.json(data); } catch (err) { next(err); // forward to error handler } }); // Pattern 2 – asyncHandler wrapper (DRY) const asyncHandler = fn => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next); app.get('/b', asyncHandler(async (req, res) => { const data = await fetchData(); // any throw is caught res.json(data); })); // Pattern 3 – express-async-errors package (global patch) require('express-async-errors'); // patch Express once app.get('/c', async (req, res) => { const data = await fetchData(); // no wrapper needed res.json(data); }); // Process-level safety net process.on('unhandledRejection', (reason) => { console.error('Unhandled Rejection:', reason); process.exit(1); // let PM2/Kubernetes restart }); process.on('uncaughtException', (err) => { console.error('Uncaught Exception:', err); process.exit(1); });
Result
Open