【发布时间】:2020-03-31 23:56:40
【问题描述】:
是否有可能在 body-parser 中发现错误的 JSON 语法?
以下代码显示了我的尝试。问题是我在收到回复时无法访问任何err.status:
SyntaxError: Unexpected token ] in JSON at position 57...
这是作为 HTML 页面提供给调用者的。我宁愿抓住那个错误并格式化一个漂亮的 JSON 作为响应。
代码尝试:
class ExampleServer extends Server {
constructor() {
...
this.app.use(bodyParser.json());
this.app.use(bodyParser.urlencoded({extended: true}));
this.app.use((err) => {
if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
Logger.Err('Bad JSON.');
}
});
...
}
}
我通过 POST 正文发送的损坏的 JSON:
{
"numberValue": 6,
"requiredValue": "some string here"]
}
我使用的body-parser和express的版本:
"body-parser": "^1.19.0",
"express": "^4.17.1",
如何捕获损坏的 JSON 错误?
【问题讨论】:
标签: node.js json express error-handling body-parser