Skip to content
Advertisement

Node.js – Handle body-parser invalid JSON error

I’m using the body-parser package like this:

JavaScript

When a valid input like { "foo": "bar" } is received everything works fine and I can access the parsed object with req.body.

However, when invalid (non-JSON) data is sent:

JavaScript

I get this error:

JavaScript

How can I handle this properly to prevent the server from shutting down?

Advertisement

Answer

One option is to add a custom error handler middleware and add a check to catch JSON parsing errors like that one:

JavaScript

Another option is to wrap body-parser‘s middleware to catch errors coming only from there:

JavaScript

Or if you want to reuse this functionality to catch different errors from different middlewares, you can do:

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