Koa 中的錯誤處理
不像 express 中在末尾處註冊一個宣告為(err, req, res, next)
中介軟體的方式,koa 剛好相反,在開頭進行註冊。
app.use(async (ctx, next) => { try { await next(); } catch (err) { ctx.status = err.status || 500; ctx.body = err.message; ctx.app.emit("error", err, ctx); } });
這樣程式中任何報錯都會收斂到此處。此時可以方便地將錯誤列印到頁面,開發時非常便捷。
+ctx.app.emit('error', err, ctx);
koa 也建議通過 app 來派發錯誤,然後通過監聽 app 上的error
事件對這些錯誤做進一步的統一處理和集中管理。
app.on("error", (err, ctx) => { /* 錯誤的集中處理: *log 出來 *寫入日誌 *寫入資料庫 *... */ });
一個錯誤捕獲並列印到頁面的示例:
const Koa = require("koa"); const app = new Koa(); app.use(async (ctx, next) => { try { await next(); } catch (err) { const status = err.status || 500; ctx.status = status; ctx.type = "html"; ctx.body = ` <b>${status}</b> ${err} `; // emmit ctx.app.emit("error", err, ctx); } }); app.use(ctx => { const a = "hello"; a = "hello world!"; // TypeError: Assignment to constant variable. ctx.body = a; }); app.on("error", (err, ctx) => { console.error("Ooops..\n", err); }); app.listen(3000);
通過node server.js
啟動後訪問頁面可看到命令列的錯誤輸出。
如果使用 pm2,可通過—no-daemon
引數使其停留在在命令列以檢視輸出。
如果不使用上述引數,可通過pm2 logs [app-name]
來檢視。
ctx.throw
樸素的拋錯方式需要手動設定狀態碼及資訊對客戶端的可見性。
const err = new Error("err msg"); err.status = 401; err.expose = true; throw err;
expose
決定是否會返回錯誤詳情給客戶端,否則只展示狀態對應的錯誤文案,比如 500 會在瀏覽器中展示為Internal Server Error
。
而通過
ctx.throw
這個 helper 方法會更加簡潔。
上面的程式碼片段等價於:
ctx.throw(401, "err msg");
如果不指定狀態碼,預設為 500。5xx 類錯誤expose
預設為false
,即不會將錯誤資訊返回到 response。
拋錯時還可以傳遞一些額外資料,這些資料會合併到錯誤物件上,在處理錯誤的地方可以從error
上獲取。
app.use(ctx => { ctx.throw(401, "access_denied", { user: { name: "foo" } }); }); app.on("error", (err, ctx) => { console.error("Ooops..\n", err.user); });