Trung BìnhNode.js iconNode.js

Error handling middleware trong Express hoạt động như thế nào?

Error handling middleware có 4 tham số (err, req, res, next) — phải đăng ký CUỐI CÙNG sau tất cả routes.

  • Pattern tốt nhất: tạo custom AppError class class AppError extends Error { constructor(public statusCode: number, message: string, public isOperational = true) { super(message) } } — phân biệt operational errors (404, validation fail — dự đoán được) vs programming errors (null reference — bugs).
  • Async error wrapper để tránh try/catch lặp lại: const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next).
  • Centralized error handler kiểm tra err.isOperational: nếu true thì gửi message cho client, nếu false thì log và trả 500 generic.
  • Express 5 async routes tự động forward error nên không cần wrapper nữa.

Pitfall: quên next tham số thứ 4 → Express không nhận ra là error handler.

Xem toàn bộ Node.js cùng filter theo level & chủ đề con.

Mở danh sách Node.js