title: How to catch this error NodeJs/Express?
body: <p>I'm trying to write simple web service using NodeJs. I make Ajax call as below:</p>
  
  <pre><code>$.ajax({
      type: "POST",
      url: "http://localhost:3800",
  
      // this json below is invalid and I need to verify it on server side
      data: '"jhhjh":"ssss"}',
  
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(data){ console.log(data);
      },
      failure: function(errMsg) {
          console.log(errMsg);
      }
  });
  </code></pre>
  
  <p>Then on server side I have this code:</p>
  
  <pre><code>var express = require("express"),
      app = express(),
      bodyParser = require('body-parser');
  
  
  app.use(bodyParser());
  
  app.all('/', function(req, res, next) {
      // set origin policy etc so cross-domain access wont be an issue
  
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  
      // that is the line that gives me error message and cannot return anything back to client
      res.send("all good");
  });
  
  app.post('/', function(req, res) {
  
  
  });
  
  app.listen(process.env.PORT || 3800);
  </code></pre>
  
  <p>However as json I'm trying to pass to server is invalid my Express crashes and I cant do anything about this. I cant catch it or anything. How can I catch this error?</p>
  
  <pre><code>Error: invalid json
      at parse (C:\xampp\htdocs\testing\node_modules\body-parser\index.js:60:15)
      at C:\xampp\htdocs\testing\node_modules\body-parser\index.js:156:18
      at IncomingMessage.onEnd (C:\xampp\htdocs\testing\node_modules\body-parser\node_modules\raw-body\index.js:113:7)
      at IncomingMessage.g (events.js:180:16)
      at IncomingMessage.EventEmitter.emit (events.js:92:17)
      at _stream_readable.js:920:16
      at process._tickCallback (node.js:415:13)
  </code></pre>
  
  <p>How can I catch this error? What I need is to detect if json passed is invalid and return <code>400</code> with json message <code>{ "someerror":"somemessage"}</code></p>