title: Node.js with Express - throw Error vs next(error)
body: <p>Can someone expound on the times when it's appropriate in a node.js Express app to throw an error like so:</p>
  
  <pre><code>throw new Error('my error');
  </code></pre>
  
  <p>or to pass this error on via the callback usually labelled 'next' like so:</p>
  
  <pre><code>next(error);
  </code></pre>
  
  <p>and could you please explain what each of them will do in the context of an Express app?</p>
  
  <p>for example, here is an express function dealing with URL parameters:</p>
  
  <pre><code>app.param('lineup_id', function (req, res, next, lineup_id) {
          // typically we might sanity check that user_id is of the right format
          if (lineup_id == null) {
              console.log('null lineup_id');
              req.lineup = null;
              return next(new Error("lineup_id is null"));
          }
  
          var user_id = app.getMainUser()._id;
          var Lineup = app.mongooseModels.LineupModel.getNewLineup(app.system_db(), user_id);
          Lineup.findById(lineup_id, function (err, lineup) {
              if (err) {
                  return next(err);
              }
              if (!lineup) {
                  console.log('no lineup matched');
                  return next(new Error("no lineup matched"));
              }
              req.lineup = lineup;
              return next();
          });
      });
  </code></pre>
  
  <p>In the line commented "//should I create my own error here?"
  I could used "throw new Error('xyz')", but what exactly would that do? Why is it usually better to pass the error to the callback 'next'?</p>
  
  <p>Another question is - how do I get "throw new Error('xyz')" to show up in the console as well as the browser when I am in development?</p>