简体   繁体   English

如何在express.js中的JSON帖子中捕获错误

[英]How can I catch errors in a JSON post in express.js

I am creating an API in express.js where by the user posts JSON. 我正在用用户发布JSON的express.js中创建一个API。

I've set the content type to application/json in the clients request. 我已经在客户端请求中将内容类型设置为application / json。 If I post valid JSON, all is well. 如果我发布有效的JSON,一切都很好。 However, posintg malformed JSON results in express throwing the following error... 但是,posintg格式错误的JSON会导致Express抛出以下错误...

string(370) "SyntaxError: Unexpected token } at Object.parse (native) at IncomingMessage. (/var/www/vhost/rest-v1/node/node_modules/express/node_modules/connect/lib/middleware/json.js:76:27) at IncomingMessage.EventEmitter.emit (events.js:92:17) at _stream_readable.js:910:16 at process._tickCallback (node.js:415:13)" 字符串(370)“ SyntaxError:意外令牌}位于IncomingMessage的Object.parse(本机)。(/ var / www / vhost / rest-v1 / node / node_modules / express / node_modules / connect / lib / middleware / json.js: 76:27)在IncomingMessage.EventEmitter.emit(events.js:92:17)在_stream_visible.js:910:16在process._tickCallback(node.js:415:13)”

How can I catch this error so that I can respond with a more meaningful error message to the user? 如何捕获此错误,以便向用户提供更有意义的错误消息?

User Express的内置错误处理中间件或使用您自己的中间件覆盖: http : //expressjs.com/guide.html#error-handling

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM