title: How to console.log an error with stack trace in node.js?
body: <p>I've been trying to debug my node app to find the source of an error in my log that shows up only as "<code>Error: Can't set headers after they are sent</code>", with no trace information or any context.</p>
  
  <p>As it happens, I think I've now fixed this... I am using <a href="https://www.npmjs.com/package/connect-timeout" rel="noreferrer"><code>connect-timeout</code></a> and I was continuing processing a callback passed to an asynchronous network operation, which callback would eventually try to do a <code>res.send()</code>, despite <code>req.timedout</code> having been set to 'true' by <code>connect-timeout</code> during the network operation.</p>
  
  <p>BUT I still can't understand why my log wasn't showing trace information for this error. Anywhere that an error is returned in my code I log it to the console with:</p>
  
  <pre><code>console.log(err);
  </code></pre>
  
  <p>If there is trace information available in the <code>err</code> object, and this seems to be placed in <code>err.stack</code>, shouldn't the above statement dump the <em>whole content</em> of <code>err</code> (including <code>err.stack</code>) to the console log?  My understanding is that I wouldn't be losing any information by doing the above, compared e.g. to:</p>
  
  <pre><code>console.log(err.stack);
  </code></pre>
  
  <p>But posts like <a href="https://stackoverflow.com/a/33593443/4070848">this one</a> seem to suggest otherwise (though the linked post has now been updated).</p>
  
  <p>I actually go further, and add some relevant text to help locate the error:</p>
  
  <pre><code>console.log('error in dodgyFunction:', err);
  </code></pre>
  
  <p>But despite this, I was still only getting "<code>Error: Can't set headers after they are sent</code>", without any of the context I'd put it.  Would this be because this console error message is output within an external library (like <code>express</code>)?  I thought that external libraries should send errors back to the main code to be dealt with accordingly?</p>
  
  <p>Edit: here's an example of where I put my error and timeout checking, at the top of the callback function passed to the async operation:</p>
  
  <pre><code>var execFile = require('child_process').execFile;
  execFile('dodgycommand', options, function(error, stdout, stderr) {
      if (req.timedout) {
          console.log('timeout detected whilst running dodgycommand, so aborting...');
          return;
      }
      if (error) {
          console.log('error running dodgycommand:', error);
          res.sendStatus(400);
          return;
      }
  
      // ... it's safe to continue ...
  
  }
  </code></pre>
  
  <p>I basically follow this same pattern throughout.</p>