NodeJS SyntaxError: Unexpected string in JSON at position 16

Raz picture Raz · Aug 1, 2018 · Viewed 7.6k times · Source

I am using body-parser middleware in order to handle JSON requests bodies in REST API.

I have tried to "hack" and test how the system handles such an input:

// Note the "form": "a" does not include the required ","
{
    "from": "a"
    "destination": "Netanya",
    "date": {
        "start": "15-07-2018"
    }
}

Now I do not know where I can catch such an error of bad input syntax.

I have tried to remove the body-parser and error is not thrown, but of course, then I cannot have the data in the req.body.

Answer

Hardik Shah picture Hardik Shah · Aug 1, 2018

As mentioned here and tested below code:

app.use(bodyParser.json());

app.use(function (error, req, res, next) {
  if(error instanceof SyntaxError){ //Handle SyntaxError here.
    return res.status(500).send({data : "Invalid data"});
  } else {
    next();
  }
});

UPDATE=========

There are six types of errors:

  1. EvalError: Raised when the eval() functions is used in an incorrect manner.
  2. RangeError: Raised when a numeric variable exceeds its allowed range.
  3. ReferenceError: Raised when an invalid reference is used.
  4. SyntaxError: Raised when a syntax error occurs while parsing JavaScript code.
  5. TypeError: Raised when the type of a variable is not as expected.
  6. URIError: Raised when the encodeURI() or decodeURI() functions are used in an incorrect manner.