title: Node.js MySQL Error Handling
body: <p>I've read several examples for using mysql in node.js and I have questions about the error handling.</p>
  
  <p>Most examples do error handling like this (perhaps for brevity):</p>
  
  <pre><code>app.get('/countries', function(req, res) {
  
      pool.createConnection(function(err, connection) {
          if (err) { throw err; }
  
          connection.query(sql, function(err, results) {
              if (err) { throw err; }
  
              connection.release();
  
              // do something with results
          });
      });
  });
  </code></pre>
  
  <p>This causes the server to crash every time there's an sql error. I'd like to avoid that and keep the server running.</p>
  
  <p>My code is like this:</p>
  
  <pre><code>app.get('/countries', function(req, res) {
  
      pool.createConnection(function(err, connection) {
          if (err) {
              console.log(err);
              res.send({ success: false, message: 'database error', error: err });
              return;
          }
  
          connection.on('error', function(err) {
              console.log(err);
              res.send({ success: false, message: 'database error', error: err });
              return;
          });
  
          connection.query(sql, function(err, results) {
              if (err) {
                  console.log(err);
                  res.send({ success: false, message: 'query error', error: err });
                  return;
              }
  
              connection.release();
  
              // do something with results
          });
      });
  });
  </code></pre>
  
  <p>I'm not sure if this is the best way to handle it. I'm also wondering if there should be a <code>connection.release()</code> in the query's <code>err</code> block. Otherwise the connections might stay open and build up over time.</p>
  
  <p>I'm used to Java's <code>try...catch...finally</code> or <code>try-with-resources</code> where I can "cleanly" catch any errors and close all my resources at the end. Is there a way to propagate the errors up and handle them all in one place?</p>