Raz*_*Raz 3 error-handling node.js body-parser
我正在使用body-parser中间件来处理 REST API 中的 JSON 请求正文。
我试图“破解”并测试系统如何处理这样的输入:
// Note the "form": "a" does not include the required ","
{
"from": "a"
"destination": "Netanya",
"date": {
"start": "15-07-2018"
}
}
Run Code Online (Sandbox Code Playgroud)
现在我不知道在哪里可以捕获这种错误输入语法的错误。
我试图删除正文解析器并且没有抛出错误,但是当然,我不能在req.body.
正如这里提到的并测试了下面的代码:
app.use(bodyParser.json());
app.use(function (error, req, res, next) {
if(error instanceof SyntaxError){ //Handle SyntaxError here.
return res.status(500).send({data : "Invalid data"});
} else {
next();
}
});
Run Code Online (Sandbox Code Playgroud)
有六种类型的错误: