「錯誤回應要長什麼樣子」是每個新專案都會討論一次的問題。其實已經有標準答案:RFC 9457 Problem Details(取代舊的 RFC 7807)。
基本格式
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
{
"type": "https://api.example.com/problems/validation-error",
"title": "輸入資料驗證失敗",
"status": 422,
"detail": "有 2 個欄位不符合規定",
"instance": "/orders/42"
}
| 欄位 | 意義 |
|---|---|
type |
錯誤類型的 URI,用戶端以它判斷錯誤種類 |
title |
給人看的簡短說明,同一類型固定不變 |
status |
HTTP 狀態碼 |
detail |
這一次錯誤的具體說明 |
instance |
發生錯誤的資源或請求 |
擴充欄位
標準允許加上自訂欄位,驗證錯誤通常會列出每個欄位:
{
"type": "https://api.example.com/problems/validation-error",
"title": "輸入資料驗證失敗",
"status": 422,
"errors": [
{ "pointer": "/email", "detail": "Email 格式不正確" },
{ "pointer": "/quantity", "detail": "數量必須大於 0" }
],
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736"
}
pointer 使用 JSON Pointer 格式,前端可以直接對應到表單欄位。trace_id 讓客服或工程師能在日誌中找到這次請求。
統一的錯誤處理
以 Express 為例,用一個錯誤處理中介層集中轉換:
class Problem extends Error {
constructor(status, type, title, extra = {}) {
super(title);
Object.assign(this, { status, type, title, ...extra });
}
}
app.use((err, req, res, next) => {
const status = err.status ?? 500;
res.status(status).type('application/problem+json').json({
type: err.type ?? 'about:blank',
title: status >= 500 ? '伺服器發生錯誤' : err.title,
status,
detail: status >= 500 ? undefined : err.detail,
errors: err.errors,
trace_id: req.traceId,
});
});
CAUTION
5xx 錯誤不要把例外訊息或堆疊追蹤回傳給用戶端,裡面可能含有 SQL、檔案路徑等內部資訊。詳細內容只寫進日誌。
type 用 URI 的好處
type 指向的網址可以放一份說明文件,告訴開發者這個錯誤的原因與處理方式。不打算提供文件時,可以使用 about:blank,這時 title 應該等於狀態碼的標準說明。
發表留言