Async Errors
Express 4 mein async handler ke andar throw hua error AUTOMATICALLY nahi pakda jaata — request HANG ho jaati hai. Har async route mein try/catch karke next(err) call karna padta hai.
Repetition se bachne ke liye EK WRAPPER banaya jaata hai jo promise ko catch karke next par bhej de. Express 5 mein ye behaviour built-in ho gaya hai — async handlers ke rejections khud error middleware tak pahunch jaate hain.
const asyncH = (fn) => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next);
app.get("/users/:id", asyncH(async (req, res) => {
const user = await db.findUser(req.params.id); // reject hua to next(err)
if (!user) { const e = new Error("Not found"); e.status = 404; throw e; }
res.json(user);
}));- Express 4 async errors automatically nahi pakadta — request hang ho jaati hai
- try/catch + next(err), ya ek asyncH wrapper use karo
- Express 5 mein async rejections built-in error middleware tak pahunchte hain
Express 4 handler ko synchronously call karta hai aur try/catch se sirf SYNC throws pakadta hai. Async function turant ek Promise return karta hai — error baad mein reject ke roop mein aata hai, jab Express ka try/catch block khatam ho chuka hota hai. Isliye request adhoori latki rehti hai.
// Ye error CHHOOT jaayega — request hang
app.get("/x", async (req, res) => {
const d = await mayFail(); // reject hua to koi nahi pakdega
res.json(d);
});Standard solution ek chhota wrapper hai jo har async handler ke promise par .catch(next) laga deta hai. Express 5 mein ye behaviour framework mein hi aa gaya hai — async handler ka rejection apne aap error middleware tak pahunchta hai, wrapper ki zaroorat nahi rehti.
const asyncH = (fn) => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next);
app.get("/x", asyncH(async (req, res) => {
res.json(await mayFail()); // ab error handler tak pahunchega
}));