我目前正在使用带有Express的bodyParser来接受JSON请求。每当我传入一个错误形成的JSON对象时,它都会通过端点返回一个讨厌的错误,并将其记录到控制台。以下是错误:
SyntaxError: Unexpected string
at Object.parse (native)
at parse (/Users/ddibiase-mbp/Documents/Projects/theride_api/node_modules/body-parser/lib/types/json.js:88:17)
at /Users/ddibiase-mbp/Documents/Projects/theride_api/node_modules/body-parser/lib/read.js:108:18
at done (/Users/ddibiase-mbp/Documents/Projects/theride_api/node_modules/body-parser/node_modules/raw-body/index.js:239:14)
at IncomingMessage.onEnd (/Users/ddibiase-mbp/Documents/Projects/theride_api/node_modules/body-parser/node_modules/raw-body/index.js:285:7)
at IncomingMessage.g (events.js:199:16)
at IncomingMessage.emit (events.js:104:17)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
SyntaxError: Unexpected string
at Object.parse (native)
at parse (/Users/ddibiase-mbp/Documents/Projects/theride_api/node_modules/body-parser/lib/types/json.js:88:17)
at /Users/ddibiase-mbp/Documents/Projects/theride_api/node_modules/body-parser/lib/read.js:108:18
at done (/Users/ddibiase-mbp/Documents/Projects/theride_api/node_modules/body-parser/node_modules/raw-body/index.js:239:14)
at IncomingMessage.onEnd (/Users/ddibiase-mbp/Documents/Projects/theride_api/node_modules/body-parser/node_modules/raw-body/index.js:285:7)
at IncomingMessage.g (events.js:199:16)
at IncomingMessage.emit (events.js:104:17)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
我想知道如何能够完全抑制错误或修补错误。我已经调查了错误,但找不到任何具体的修补建议。
答案 0 :(得分:2)
通过Express:
声明error handler是很常见的app.use(function(err, req, res, next) {
...
return res.sendStatus(500);
});
这也会捕获像body-parser
这样的中间件中抛出的错误。