Skip to content
Advertisement

Catch express bodyParser error

I want to catch the error from the bodyParser() middleware when I send a json object and it is invalid because I want to send a custom response instead of a generic 400 error.

This is what I have and it works:

JavaScript

But this seems to me a very ugly approach because I’m comparing the error message which could change in future express versions. There’s any other way to catch bodyParser() errors?

EDIT:

This is the error when the request body has an invalid json:

JavaScript

Pretty printed stack:

JavaScript

Advertisement

Answer

Ok, found it:

bodyParser() is a convenience function for json(), urlencoded() and multipart(). I just need to call to json(), catch the error and call to urlencoded() and multipart().

bodyParser source

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement