title: Expressjs - Handling Errors With Middleware
body: <p>I'm building an API (using Expressjs v4) and typically I've dealt with errors within the route rather than using middleware. For example:</p>
  
  <pre><code>router.use('/', function(req, res, next) {
    ...
    if (err)
      return res.status(500).send({type: "serverError", message: "Something has gone wrong on our end."});
  }
  </code></pre>
  
  <p>I now realise that middleware is the "way to go." I've seen the rather limited documentation on the Expressjs site here: <a href="http://expressjs.com/guide/error-handling.html">http://expressjs.com/guide/error-handling.html</a> but still unsure of a few things.</p>
  
  <p>I've added in the <code>server.js</code>:</p>
  
  <pre><code>function errorHandler(err, req, res, next) {
  
  }
  </code></pre>
  
  <p><strong>but how do I supposed to handle the different types of errors (400,404,500 etc)?</strong></p>
  
  <p>I'm finding myself writing 3 lines of code each time an error occurs:</p>
  
  <pre><code>//A route
  var err = new Error();
  err.status = 404;
  return next(err);
  </code></pre>
  
  <p>and I can access the status using:</p>
  
  <pre><code>function errorHandler(err, req, res, next) {
    console.log(err.status);
    if(err.status == "400")
      //do something
    else
      //etc etc
  }
  </code></pre>
  
  <p>Surely there's an easier way than this? Am I missing something?</p>