पाठ 16 / 25

असिंक्रोनस एरर हैंडलिंग

next, wrappers या Express 5 की automatic promise handling से async handlers की errors आगे भेजें।

एक ख़तरा

Express 4 में async route handler के अंदर rejected promise आपके error middleware तक नहीं पहुँचती; उसे next(err) से आगे भेजना पड़ता है। Express 5 (अब npm पर default) इसे अपने-आप आगे भेजता है।

पकड़ें और आगे भेजें

बॉडी को try/catch में लपेटें और next(err) बुलाएँ — या दोहराव से बचने के लिए एक छोटा हेल्पर उपयोग करें।

const asyncHandler = (fn) => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next);

app.get('/users/:id', asyncHandler(async (req, res) => {
  const user = await db.users.findById(req.params.id);
  if (!user) {
    const err = new Error('User not found');
    err.status = 404;
    throw err;
  }
  res.json(user);
}));

Express 5 इसे ठीक करता है

Express 5, async हैंडलर से रिजेक्ट हुए promise को अपने-आप next(err) तक भेजता है — Express 5 पर wrapper की ज़रूरत नहीं रहती।