2

I am creating an API in express.js where by the user posts JSON.

I've set the content type to application/json in the clients request. If I post valid JSON, all is well. However, posintg malformed JSON results in express throwing the following error...

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)"

How can I catch this error so that I can respond with a more meaningful error message to the user?

1 Answer 1

1

User Express's built in error handling middleware or override it with your own: http://expressjs.com/guide.html#error-handling

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for that. I have since found this, but I would like to handle the error differently for each route. I'm left wondering whether I need to ask another question. Is there a way of of disabling the automatic JSON parsing so that I cat do it within the route function?
The Express middleware that is parsing the JSON is called via bodyParser expressjs.com/api.html#middleware . Remove that middleware and you can instead parse it yourself in the route. However, I would recommend sticking with automatic parsing and just returning a 400 Bad Request HTTP response. Trying to deal intelligently with malformed JSON is both infinitely complex and a potential security hole.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.