title: NodeJS, express: validating request json payload on server to check JSON is not corrupt
body: <p>I am trying to develop a service to process some JSON data that is sent by a client in a POST request. I have developed the service and the functionality and it works fine if the JSON data in POST request is free of errors but if the json data in request is corrupt (missing a brace or comma) then the service breaks. I am new with node and tried error handling with try catch but that does not seem to work. Can someone please have a look at this code and error and help me figure out how to handle the errors properly in node.js</p>
  
  <p>server.js</p>
  
  <pre><code>var express = require('express');
  var bodyParser = require('body-parser');
  
  var app = express();
  app.use(bodyParser.json());
  
  app.post('/', function(request, response){
  
  response.set("Content-Type", "application/json");
  var jsonObj = request.body;
  var responseJson = {};
  if(jsonObj.hasOwnProperty("payload"))
  {
  var keyResponse = "response";
  responseJson[keyResponse] = "Here is processed data";
  response.status(200);
  }
  else
  {
      response.status(400);
      var keyResponse = "error";
      responseJson[keyResponse] = "JSON parsing failed";
  }
  response.send(responseJson);
  })
  var port = process.env.PORT || 3000;
  app.listen(port);
  console.log("Sever is up and listening on port "+port);
  </code></pre>
  
  <p>Errors:</p>
  
  <pre><code>SyntaxError: Unexpected token p in JSON at position 6
  at JSON.parse (&lt;anonymous&gt;)
  at parse (/Users/Vov/Desktop/NineEntertainmentService/nine-service/node_modules/body-parser/lib/types/json.js:88:17)
  at /Users/Vov/Desktop/NineEntertainmentService/nine-service/node_modules/body-parser/lib/read.js:116:18
  at invokeCallback (/Users/Vov/Desktop/NineEntertainmentService/nine-service/node_modules/raw-body/index.js:262:16)
  at done (/Users/Vov/Desktop/NineEntertainmentService/nine-service/node_modules/raw-body/index.js:251:7)
  at IncomingMessage.onEnd (/Users/Vov/Desktop/NineEntertainmentService/nine-service/node_modules/raw-body/index.js:307:7)
  at emitNone (events.js:86:13)
  at IncomingMessage.emit (events.js:185:7)
  at endReadableNT (_stream_readable.js:974:12)
  at _combinedTickCallback (internal/process/next_tick.js:74:11)
  </code></pre>
  
  <p>This is an error from when I fed a request with JSON data missing a colon(:)</p>
  
  <p>Any help is appreciated! Thanks</p>