Nâng CaoNode.js iconNode.js

Error handling strategy cho production Node.js?

Trong production Node.js, cần phân biệt rõ hai loại lỗi để xử lý khác nhau. Operational errors là lỗi dự kiến được như user gửi data sai (400), không có quyền (401), hoặc resource không tồn tại (404) — xử lý gracefully bằng cách trả HTTP status phù hợp và message rõ ràng.

Programming errors là bugs thật sự như TypeError hay null reference — cách tốt nhất là để process crash rồi tự restart bằng PM2 hoặc Docker, vì app đang ở trạng thái không xác định. Cần có global handlers process.on('uncaughtException')process.on('unhandledRejection') để log lỗi trước khi crash.

Kết hợp logging library như Winston hoặc Pino với log levels (error, warn, info, debug) và format JSON để dễ parse bởi log aggregators.

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

Mở danh sách Node.js