
- Koa.js 教程
- Koa.js - 主頁
- Koa.js - 概述
- Koa.js - 環境
- Koa.js - Hello World
- Koa.js - 生成器
- Koa.js - 路由
- Koa.js - URL 構建
- Koa.js - HTTP 方法
- Koa.js - Request 物件
- Koa.js - Response 物件
- Koa.js - 重定向
- Koa.js - 錯誤處理
- Koa.js - 級聯
- Koa.js - 模板
- Koa.js - 表單資料
- Koa.js - 檔案上傳
- Koa.js - 靜態檔案
- Koa.js - Cookie
- Koa.js - 會話
- Koa.js - 認證
- Koa.js - 壓縮
- Koa.js - 快取
- Koa.js - 資料庫
- Koa.js - RESTful API
- Koa.js - 日誌
- Koa.js - 腳手架
- Koa.js - 資源
- Koa.js 有用資源
- Koa.js - 快速指南
- Koa.js - 有用資源
- Koa.js - 討論
Koa.js - 錯誤處理
錯誤處理在構建 Web 應用程式中起著重要作用。Koa 還為此使用中介軟體。
在 Koa 中,將作為第一個中介軟體之一新增一個執行 try { yield next } 的中介軟體。如果我們遇到任何下游錯誤,我們將返回到相關的 catch 子句並在此處處理錯誤。例如 −
var koa = require('koa'); var app = koa(); //Error handling middleware app.use(function *(next) { try { yield next; } catch (err) { this.status = err.status || 500; this.body = err.message; this.app.emit('error', err, this); } }); //Create an error in the next middleware //Set the error message and status code and throw it using context object app.use(function *(next) { //This will set status and message this.throw('Error Message', 500); }); app.listen(3000);
我們在上面的程式碼中故意建立了一個錯誤,並在我們第一個中介軟體的 catch 塊中處理錯誤。然後,它將顯示在我們的控制檯上,並作為響應傳送給我們的客戶端。引發此錯誤時,我們收到的錯誤訊息如下。
InternalServerError: Error Message at Object.module.exports.throw (/home/ayushgp/learning/koa.js/node_modules/koa/lib/context.js:91:23) at Object.<anonymous> (/home/ayushgp/learning/koa.js/error.js:18:13) at next (native) at onFulfilled (/home/ayushgp/learning/koa.js/node_modules/co/index.js:65:19) at /home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5 at Object.co (/home/ayushgp/learning/koa.js/node_modules/co/index.js:50:10) at Object.toPromise (/home/ayushgp/learning/koa.js/node_modules/co/index.js:118:63) at next (/home/ayushgp/learning/koa.js/node_modules/co/index.js:99:29) at onFulfilled (/home/ayushgp/learning/koa.js/node_modules/co/index.js:69:7) at /home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5
現在,傳送到伺服器的任何請求都將導致此錯誤。
廣告