[TOC]
### Koa2 異常處理
* [ ] 自定義異常

>[danger] 定義一個全局異常處理類 http-exceptions.js
~~~
// 自定義異常
class HttpExceptions extends Error {
constructor(msg='服務器異常', errorCode = 0, code = 400) {
super()
this.msg = msg
this.errorCode = errorCode
this.code = code
}
}
// 資源未找到異常
class ResourceErr extends HttpExceptions {
constructor(msg='資源未找到', errorCode = 1, code = 404) {
super(msg, errorCode, code)
}
}
module.exports = {
HttpExceptions,
ResourceErr
}
~~~
*****
* [ ] 定義一個全局捕獲異常中間件

~~~
const { HttpExceptions } = require('../core/http-exceptions')
// 全局異常捕捉中間件
const Exception = async (ctx, next) => {
try {
await next()
} catch(error) {
const { msg, errorCode, code } = error
const url = `${ctx.method} : ${ctx.request.path}`
if (error instanceof HttpExceptions) {
// 已知異常
ctx.body = { msg, errorCode, url }
ctx.status = code
} else {
// 未知異常
ctx.body = { msg: '服務器內部錯誤~', errorCode: 999, url }
ctx.status = 500
}
}
}
module.exports = Exception
~~~
*****
* [ ] 使用
~~~
const Router = require('koa-router')
const router = new Router()
const { ResourceErr } = require('../../../core/http-exceptions')
router.get('/api/v1/news/:id', (ctx, next) => {
// 自定義異常
throw new ResourceErr()
})
module.exports = router
~~~
- 序言
- ES6模塊化
- node基礎
- FS模塊
- 常用變量
- crypto加密
- 基礎
- 安裝
- 中間件
- 架構
- 結構分層
- 配置
- 路由
- 安裝路由
- 自動加載
- 獲取參數
- 路由前綴
- 路由中間件
- 控制器
- 請求
- 請求信息
- 數據庫
- mongoDB
- mongoDB原生語句
- mongoDB數據庫角色
- mongoose連接數據庫
- 自動記錄時間戳
- 模型
- mongoose模型
- 定義
- 模型初始化
- 查詢
- 新增
- 更新
- 刪除
- 隱藏字段
- 模式
- 關聯查詢
- 復雜模型
- 仿知乎個人資料建模
- 關注與粉絲
- 視圖
- 模板
- edge
- 日志
- 錯誤和調試
- 調試當前文件
- nodemon調試
- 異常處理
- Koa2錯誤處理
- 驗證
- Koa驗證器
- async-validator
- installation
- 安全
- 數據加密
- 雜項
- jwt
- koa-jwt
- env環境變量配置
- 上傳
- 分頁和模糊搜索
- 擴展
- nodemon
- bodyparser
- koaJsonError
- cross-env
- uuid生成唯一ID
- pope字符串模板引擎
- 命令行
- 部署
- 附錄
- RESTfulApi
- Http動詞
- 狀態碼
- 調用頻率限制
- 按需查詢字段
- restful分頁