I want to catch the error from the bodyParser() middleware when I send a json object and it is invalid because I want to send a custom response instead of a generic 400 error.
This is what I have and it works:
JavaScript
x
10
10
1
app.use (express.bodyParser ());
2
app.use (function (error, req, res, next){
3
//Catch bodyParser error
4
if (error.message === "invalid json"){
5
sendError (res, myCustomErrorMessage);
6
}else{
7
next ();
8
}
9
});
10
But this seems to me a very ugly approach because I’m comparing the error message which could change in future express versions. There’s any other way to catch bodyParser() errors?
EDIT:
This is the error when the request body has an invalid json:
JavaScript
1
8
1
{
2
stack: 'Error: invalid jsonn at Object.exports.error (<path>/node_modules/express/node_modules/connect/lib/utils.js:55:13)n at IncomingMessage.<anonymous> (<path>/node_modules/express/node_modules/connect/lib/middleware/json.js:74:71)n at IncomingMessage.EventEmitter.emit (events.js:92:17)n at _stream_readable.js:872:14n at process._tickDomainCallback (node.js:459:13)',
3
arguments: undefined,
4
type: undefined,
5
message: 'invalid json',
6
status: 400
7
}
8
Pretty printed stack:
JavaScript
1
7
1
Error: invalid json
2
at Object.exports.error (<path>/node_modules/express/node_modules/connect/lib/utils.js:55:13)
3
at IncomingMessage.<anonymous> (<path>/node_modules/express/node_modules/connect/lib/middleware/json.js:74:71)
4
at IncomingMessage.EventEmitter.emit (events.js:92:17)
5
at _stream_readable.js:872:14
6
at process._tickDomainCallback (node.js:459:13)
7
Advertisement
Answer
Ok, found it:
bodyParser() is a convenience function for json(), urlencoded() and multipart(). I just need to call to json(), catch the error and call to urlencoded() and multipart().
JavaScript
1
9
1
app.use (express.json ());
2
app.use (function (error, req, res, next){
3
//Catch json error
4
sendError (res, myCustomErrorMessage);
5
});
6
7
app.use (express.urlencoded ());
8
app.use (express.multipart ());
9