Giao diện
@digiforce-nc/plugin-error-handler
Plugin xử lý lỗi toàn cục — middleware Koa bắt mọi exception trong request pipeline, chuẩn hóa response lỗi và xử lý đặc biệt cho Sequelize/SQL.
Plugin này làm gì?
Khi request gặp lỗi (validation, permission, SQL, runtime), plugin-error-handler đảm bảo client luôn nhận response chuẩn hóa thay vì stack trace hoặc lỗi thô. Nó là lưới an toàn của toàn bộ HTTP pipeline.
Hai nhiệm vụ chính
| # | Nhiệm vụ | Chi tiết |
|---|---|---|
| 1 | Bắt exception | Wrap toàn bộ downstream middleware trong try-catch |
| 2 | Chuẩn hóa response | Chuyển mọi loại lỗi thành format thống nhất { errors: [...] } |
Kiến trúc
Vị trí trong middleware chain
Plugin đăng ký middleware sau i18n (để dùng được hàm dịch) và trước cors — đảm bảo bắt được lỗi từ tất cả middleware downstream:
i18n → errorHandler → cors → auth → acl → handlerPhân loại và xử lý lỗi
Xử lý chi tiết theo loại lỗi và DB backend
| Loại lỗi | DB backend | Xử lý |
|---|---|---|
| Sequelize ValidationError | Tất cả | Trích field + message, gọi i18n dịch, trả danh sách lỗi theo field |
| UniqueConstraintError | Tất cả | Phân tích constraint name → xác định field trùng lặp |
| SQL Syntax Error | Tất cả | Sanitize message (loại bỏ chi tiết schema), trả lỗi chung |
| Invalid column | PostgreSQL | Detect column "X" does not exist |
| Invalid column | MySQL | Detect Unknown column 'X' |
| Invalid column | SQLite | Detect no such column: X |
| Invalid table | PostgreSQL | Detect relation "X" does not exist |
| Invalid table | MySQL | Detect Table 'X' doesn't exist |
| Invalid table | SQLite | Detect no such table: X |
Response format
Mọi lỗi đều trả về cùng format chuẩn:
json
{
"errors": [
{
"message": "Field 'email' must be unique",
"code": "VALIDATION_ERROR"
}
]
}Với validation error nhiều field:
json
{
"errors": [
{ "message": "Title is required", "field": "title" },
{ "message": "Email format invalid", "field": "email" }
]
}Không có API endpoint hay database
Plugin này không tạo endpoint hay bảng nào — nó là middleware thuần túy, chỉ can thiệp vào response khi có lỗi xảy ra.
Vòng đời plugin
Plugin chỉ đăng ký middleware trong beforeLoad() — không cần install() hay afterStart().
Dependencies
| Package | Vai trò |
|---|---|
@digiforce-nc/server | Server framework, middleware chain |
@digiforce-nc/database | Sequelize error types (ValidationError, UniqueConstraintError) |