JavaScript Node.js - Handle body-parser invalid JSON error

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

// For parsing application/json:
app.use(require('body-parser').json());

// For parsing application/x-www-form-urlencoded
app.use(require('body-parser').urlencoded({ extended: true })); 

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:

data: JSON.stringify("just something inappropriate"),

I get this error:

{ SyntaxError: Unexpected token " in JSON at position 0
    at JSON.parse (<anonymous>)
    at createStrictSyntaxError
    at ...
expose: true,
statusCode: 400,
status: 400,
body: '"Something"',
type: 'entity.parse.failed' }

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ...

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

Answer:1

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

app.use(require('body-parser').json()); 
app.use(require('body-parser').urlencoded({ extended: true }));

...

app.use((err, req, res, next) => {
    // This check makes sure this is a JSON parsing issue, but it might be
    // coming from any middleware, not just body-parser:

    if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
        console.error(err);
        return res.sendStatus(400); // Bad request
    }

    next();
});

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

const bodyParser = require('body-parser');

app.use((req, res, next) => {
    bodyParser.json()(req, res, err => {
        if (err) {
            console.error(err);
            return res.sendStatus(400); // Bad request
        }

        next();
    });
});

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

function handleError(middleware, errorHandler) {
    middleware(req, res, err => err ? errorHandler(err, req, res, next) : next());
}

const bodyParser = require('body-parser');

app.use(handleError(bodyParser.json(), (err, req, res, next) => {
    if (err) {
        console.error(err);
        return res.sendStatus(400); // Bad request
    }

    next();
}));
Answer:2

I'm doing some analysis on a large base, mostly javascript (it's actually mostly Siebel eScript, but that's more or less the same thing, grammatically) Over the years, bad programmers have been in ...

I'm doing some analysis on a large base, mostly javascript (it's actually mostly Siebel eScript, but that's more or less the same thing, grammatically) Over the years, bad programmers have been in ...

  1. strip comments from html
  2. strip comments from c code
  3. strip comments from json
  4. strip comments from css
  5. strip comments from xml
  6. strip comments from python
  7. strip comments from word document
  8. strip comments from java
  9. strip comments from c++ file
  10. python strip comments from file
  11. bash strip comments from file
  12. python strip comments from line
  13. linux strip comments from file
  14. php strip comments from html
  15. python strip comments from json
  16. python strip comments from sql
  17. gulp strip comments from html

I need to find a very performant way to find out if a custom element or any of its parent elements has display: none; First approach: checkVisible() { let parentNodes = []; let el = this; ...

I need to find a very performant way to find out if a custom element or any of its parent elements has display: none; First approach: checkVisible() { let parentNodes = []; let el = this; ...

How can I share pdf file link or image link which will open in react native mobile app web browser. I have added a share button but when the user clicks on it, it opens where to share menu options ...

How can I share pdf file link or image link which will open in react native mobile app web browser. I have added a share button but when the user clicks on it, it opens where to share menu options ...

<div id="parent"> <div id="child1"> <div id="child2"> <div id="child3"> <div id="child4"> </div> </...

<div id="parent"> <div id="child1"> <div id="child2"> <div id="child3"> <div id="child4"> </div> </...

  1. javascript parent elements
  2. javascript get parent elements
  3. javascript traverse parent elements
  4. javascript multiple parent elements
  5. javascript all parent elements
  6. javascript remove parent elements
  7. javascript iframe parent elements
  8. javascript get all parent elements
  9. javascript find all parent elements
  10. javascript find elements parent