I am using body-parser
middleware in order to handle JSON requests bodies in REST API.
I have tried to "hack" and test how the system handles such an input:
// Note the "form": "a" does not include the required ","
{
"from": "a"
"destination": "Netanya",
"date": {
"start": "15-07-2018"
}
}
Now I do not know where I can catch such an error of bad input syntax.
I have tried to remove the body-parser and error is not thrown, but of course, then I cannot have the data in the req.body
.
As mentioned here and tested below code:
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();
}
});
There are six types of errors: