I’m using the body-parser
package like this:
JavaScript
x
6
1
// For parsing application/json:
2
app.use(require('body-parser').json());
3
4
// For parsing application/x-www-form-urlencoded
5
app.use(require('body-parser').urlencoded({ extended: true }));
6
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
1
2
1
data: JSON.stringify("just something inappropriate"),
2
I get this error:
JavaScript
1
12
12
1
{ SyntaxError: Unexpected token " in JSON at position 0
2
at JSON.parse (<anonymous>)
3
at createStrictSyntaxError
4
at
5
expose: true,
6
statusCode: 400,
7
status: 400,
8
body: '"Something"',
9
type: 'entity.parse.failed' }
10
11
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at
12
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
1
17
17
1
app.use(require('body-parser').json());
2
app.use(require('body-parser').urlencoded({ extended: true }));
3
4
5
6
app.use((err, req, res, next) => {
7
// This check makes sure this is a JSON parsing issue, but it might be
8
// coming from any middleware, not just body-parser:
9
10
if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
11
console.error(err);
12
return res.sendStatus(400); // Bad request
13
}
14
15
next();
16
});
17
Another option is to wrap body-parser
‘s middleware to catch errors coming only from there:
JavaScript
1
13
13
1
const bodyParser = require('body-parser');
2
3
app.use((req, res, next) => {
4
bodyParser.json()(req, res, err => {
5
if (err) {
6
console.error(err);
7
return res.sendStatus(400); // Bad request
8
}
9
10
next();
11
});
12
});
13
Or if you want to reuse this functionality to catch different errors from different middlewares, you can do:
JavaScript
1
15
15
1
function handleError(middleware, errorHandler) {
2
middleware(req, res, err => err ? errorHandler(err, req, res, next) : next());
3
}
4
5
const bodyParser = require('body-parser');
6
7
app.use(handleError(bodyParser.json(), (err, req, res, next) => {
8
if (err) {
9
console.error(err);
10
return res.sendStatus(400); // Bad request
11
}
12
13
next();
14
}));
15