如何处理快速nodejs中的body-parser错误

时间:2014-12-17 08:12:33

标签: node.js error-handling body-parser

我正在使用以下数据点击Node上的Web服务,

我的请求数据是:

{
"first_name":"surinder",,
"last_name":"rawat",
"email":"surinder.rawat@testcompany.com",
"phone":"1234567890",
"password":"surinder",
"user_type":"H",
"device_type":"A"
}

并收到以下错误:

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)

我故意使用双逗号来获取此错误。我想知道如何处理此错误并以正确的格式向用户显示错误

由于

1 个答案:

答案 0 :(得分:5)

来自Docs -

您可以在其他app.use()和路由调用之后定义错误处理中间件;例如:

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!');

});