how to handle body-parser errors in express nodejs

Surinder picture Surinder · Dec 17, 2014 · Viewed 7.6k times · Source

I am hitting a web service on Node with following data,

MY request data is:

{
"first_name":"surinder",,
"last_name":"rawat",
"email":"[email protected]",
"phone":"1234567890",
"password":"surinder",
"user_type":"H",
"device_type":"A"
}

and getting following error:

Connect
400 SyntaxError: Unexpected token ,
   at Object.parse (native)
   at parse (/home/surinder/workspace/HappyHakka/node_modules/body-parser/lib/typs
   /json.js:76:17)
   at /home/surinder/workspace/HappyHakka/node_modules/body-parser/lib/read.js:98:18
   at IncomingMessage.onEnd (/home/surinder/workspace/HappyHakka/node_modules/body-parser
   /node_modules/raw-body/index.js:136:7)
   at IncomingMessage.g (events.js:180:16)
   at IncomingMessage.emit (events.js:92:17)
   at _stream_readable.js:943:16
   at process._tickCallback (node.js:419:13)

I intentionally used double comma to get this error. I want to know how to handle this error and show user an error in a proper format

Thanks

Answer

david picture david · Sep 14, 2016

From the Docs -

You define error-handling middleware last, after other app.use() and routes calls; for example:

var bodyParser = require('body-parser');
var methodOverride = require('method-override');

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(function(err, req, res, next) {

  // error handling logic
  console.error(err.stack);
  res.status(500).send('Something broke!');

});