[TOC]
### egg resfulAPI 全局異常處理
### 統一錯誤處理
* [ ] 文檔:[https://eggjs.org/zh-cn/tutorials/restful.html](https://eggjs.org/zh-cn/tutorials/restful.html)
*****
1. 自定義一個異常基類
app / exceptions / http_exceptions.js
```
class HttpExceptions extends Error {
constructor(msg='服務器異常', code=1, httpCode=400) {
super()
this.code = code;
this.msg = msg;
this.httpCode = httpCode;
}
}
module.exports = { HttpExceptions };
```
*****
2. 定義全局異常處理中間件
app / middleware / error_handler.js
```
const { HttpExceptions } = require('../exceptions/http_exceptions');
module.exports = () => {
return async function errorHandler(ctx, next) {
try {
await next();
} catch (err) {
// 所有的異常都在 app 上觸發一個 error 事件,框架會記錄一條錯誤日志
ctx.app.emit('error', err, ctx);
let status = err.status || 500;
let error = {};
if (err instanceof HttpExceptions) {
status = err.httpCode
error.requestUrl = `${ctx.method} : ${ctx.path}`;
error.msg = err.msg;
error.code = err.code;
error.httpCode = err.httpCode;
} else {
// 未知異常,系統異常,線上不顯示堆棧信息
// 生產環境時 500 錯誤的詳細錯誤內容不返回給客戶端,因為可能包含敏感信息
error.errsInfo = status === 500 && ctx.app.config.env === 'prod'
? 'Internal Server Error'
: err.message;
}
// 從 error 對象上讀出各個屬性,設置到響應中
ctx.body = error;
if (status === 422) {
ctx.body.detail = err.errors;
}
ctx.status = status;
}
};
};
```
*****
- 概述
- 起步
- 跨域配置
- 路徑別名
- 路由
- api版本控制
- 錯誤和異常
- 全局異常處理
- 數據庫
- 創建遷移文件
- sequelize數據類型
- 配置
- 新增
- 查詢
- 條件查詢
- 模糊查詢
- 排序查詢
- 聚合查詢
- 分組查詢
- 分頁查詢
- 修改
- 刪除
- 獲取器
- 修改器
- 靜態屬性
- 字段驗證
- 外鍵約束
- 關聯模型
- 一對一
- 一對多
- 左外連接
- 多對多
- 字段顯示隱藏
- 事務
- 字段自增
- 驗證層
- egg-validate
- indicative驗證器
- egg-validate-plus
- betterValidate
- 校驗規則
- 中間件
- 安全
- 數據加密
- 單向加密
- 示例代碼
- 封裝egg加密
- 上傳
- path模塊
- 單文件上傳
- 多文件上傳
- 按照日期存儲
- 工具函數
- egg常用工具函數
- 緩存
- 配置緩存插件
- 設置緩存
- 獲取緩存
- 刪除緩存
- 消息隊列
- rabbitMQ
- 安裝
- 簡單隊列
- 工作隊列
- 工作隊列(dispach分發)
- 消息應答和持久化
- redis
- 數據類型
- 字符串類型(String)
- 哈希類型(Hash)
- 列表(List)
- 無序集合(Set)
- 可排序集合(Zset)
- 郵件系統
- nodeMailer
- 第三方模塊
- 生成隨機數
- JWT
- JWT鑒權
- 生成Token
- 短信服務
- 阿里大魚短信驗證碼
- 發送短信邏輯
- 阿里短信Node類