Express 项目环境搭建 -- 7. 错误处理中间件

在开发过程中,我们会遇到各种不符合要求的请求,需要把这类请求拦下来并返回明确的错误信息,同时保证程序不会因为未知错误崩溃——错误处理就是为此存在的。

定义准确的错误信息

我们可以创建一个文件来定义一系列错误信息,在需要的时候只要传入错误码(甚至一些自定义的错误信息),就能得到想要错误信息结构,方便返回,而不再需要每次都构建一次

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// utils/errcode.js
const ERRCODE = {
0: {
status: 200,
body: {
errcode: "0",
errmsg: "ok",
},
},
40001: {
status: 400,
body: {
errcode: "40001",
errmsg: "参数错误",
},
},
40002: {
status: 400,
body: {
errcode: "40002",
errmsg: "无权访问",
},
},
40003: {
status: 400,
body: {
errcode: "40003",
errmsg: "无效 token",
},
},
40004: {
status: 400,
body: {
errcode: "40004",
errmsg: "请求太频繁,请稍后重试",
},
},
50000: {
status: 500,
body: {
errcode: "50000",
errmsg: "服务端错误",
},
},
};

function errcode(code, res = {}) {
return {
...(ERRCODE[code] || ERRCODE[50000]),
body: {
...(ERRCODE[code] || ERRCODE[50000]).body,
...res,
},
};
}

module.exports = errcode;

errcode 对错误的错误码,在文件中查找对应的对象,并封装成下面这种格式:

1
2
3
4
5
6
7
8
{
"status": 200,
"body": {
"errcode": "0",
"errmsg": "ok"
...
}
}

调用者就能得到统一的返回数据。

拦截请求并抛出错误信息

为了能自定义错误,还需要对 Error 对象重新处理

1
2
3
4
5
6
7
8
9
10
11
// utils/MyError.js
function MyError(errcode = 50000, message = {}) {
this.name = "MyError";
this.errcode = errcode;
this.resBody = message;
this.stack = new Error().stack;
}
MyError.prototype = Object.create(Error.prototype);
MyError.prototype.constructor = MyError;
// global.MyError = MyError;
module.exports = MyError;

使用自定义错误对象抛出错误

1
2
3
4
5
6
7
8
9
10
11
12
const express = require("express");
const router = express.Router();
const { MyError } = require("../../../utils/index");

router.post("", async function (req, res, next) {
try {
// ...
throw new MyError(40001, { data: {} });
} catch (err) {
next(err);
}
});

兜底所有因请求问题导致的错误

1
2
3
4
5
6
7
8
9
10
11
const express = require("express");
// require("./utils/MyError");

// 文件最后调用
app.use(function ErrorHandler(err, req, res, next) {
const error = errcode(err.errcode);
console.log(err);
res
.status(error.status)
.send({ ...error.body, ...(err.name === "MyError" ? err.resBody : {}) });
});

异步路由中的错误

Express 4 不会自动捕获 async 函数里 throw 的错误,必须 try/catch 后手动 next(err),否则 promise rejection 不会进入错误处理中间件:

1
2
3
4
5
6
7
8
router.get("/user", async function (req, res, next) {
try {
const user = await getUser(req.query.id); // 可能 reject
res.json(user);
} catch (err) {
next(err); // 手动交给错误处理中间件
}
});

Express 5 起,async 路由返回的 rejected promise 会被自动转发给错误处理中间件,可以省掉这层 try/catch。这个版本差异是升级时最常见的坑:同一段代码在 4 上可能「静默挂掉」,在 5 上才暴露成 500。

404 与 next 的语义

  • next():交给下一个匹配的中间件/路由;都不匹配时由 Express 默认返回 404。
  • next(err):跳过后续普通中间件,直接进入错误处理中间件(四参数那个)。
  • next("route"):跳过当前路由剩余的处理函数,进入下一个匹配路由,仅在 router 内有效。

自定义 404 要放在所有路由之后:

1
2
3
app.use((req, res) => {
res.status(404).json({ errcode: "40400", errmsg: "接口不存在" });
});

位置放错(比如放在路由之前)会把所有请求都截成 404。

参考链接

系列导航


Express 项目环境搭建 -- 7. 错误处理中间件
https://bubao.github.io/posts/590703af.html
作者
一念
发布于
2022年3月7日
许可协议