fix: return 400 for malformed JSON bodies (entity.parse.failed)

body-parser 的 JSON 解析失败之前会掉进通用 500 处理;现在明确返回
400 'JSON 格式无效',并把对应的测试断言收紧为精确匹配。
This commit is contained in:
lezi-fun committed 2026-10-02 12:58:56 +08:00
1 parent 0d77dc3572
commit 1ff6eb13e6
2 files changed
+5 -2

No files matched your search

+3
View File
@@ -2604,6 +2604,9 @@ app.use((err, req, res, next) => {
if (err.type === 'entity.too.large') {
return res.status(413).json({ error: '请求内容过大' });
}
if (err.type === 'entity.parse.failed') {
return res.status(400).json({ error: 'JSON 格式无效' });
}
if (err.message === 'Origin is not allowed by CORS') {
return res.status(403).json({ error: '不允许的跨域来源' });
}
+2 -2
View File
@@ -94,6 +94,6 @@ test('malformed JSON bodies are rejected without crashing the server', async ()
.set('X-Forwarded-For', ip)
.set('Content-Type', 'application/json')
.send('{not valid json');
assert.ok(res.status >= 400);
assert.ok(res.body.error);
assert.equal(res.status, 400);
assert.equal(res.body.error, 'JSON 格式无效');
});