Bỏ qua, đến nội dung

@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
1Bắt exceptionWrap toàn bộ downstream middleware trong try-catch
2Chuẩn hóa responseChuyể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 → handler

Phân loại và xử lý lỗi

Xử lý chi tiết theo loại lỗi và DB backend

Loại lỗiDB backendXử lý
Sequelize ValidationErrorTất cảTrích field + message, gọi i18n dịch, trả danh sách lỗi theo field
UniqueConstraintErrorTất cảPhân tích constraint name → xác định field trùng lặp
SQL Syntax ErrorTất cảSanitize message (loại bỏ chi tiết schema), trả lỗi chung
Invalid columnPostgreSQLDetect column "X" does not exist
Invalid columnMySQLDetect Unknown column 'X'
Invalid columnSQLiteDetect no such column: X
Invalid tablePostgreSQLDetect relation "X" does not exist
Invalid tableMySQLDetect Table 'X' doesn't exist
Invalid tableSQLiteDetect 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

PackageVai trò
@digiforce-nc/serverServer framework, middleware chain
@digiforce-nc/databaseSequelize error types (ValidationError, UniqueConstraintError)

Mục lục chi tiết