Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching Illegal JSON POST Data in Express?

When creating a POST request with valid JSON, the bodyParser parses the body of the POST request correctly. However, if I submit an invalid JSON string as the body, I receive the error:

SyntaxError: Unexpected token ILLEGAL
at parse (native)
at IncomingMessage.<anonymous>(/home/.../middleware/bodyParser.js:69:15)
...

So, it appears that the body parser is failing during the parsing of the body. However, I would like to catch this failure and return an error. I'm unsure what I can do to catch it, so any help would be appreciated. Thanks.

like image 218
naivedeveloper Avatar asked Sep 20 '11 00:09

naivedeveloper


1 Answers

This is in the connect.js bodyParser middleware. It DOES do a try/catch and then calls next(err). You should be able to catch this error and handle with additional custom code using the app.error() callback hook. http://expressjs.com/guide.html#error-handling

like image 186
Peter Lyons Avatar answered Sep 26 '22 17:09

Peter Lyons