title: What's the right way to create error messages that get returned in an Express request?
body: <p>I have a function called <code>a</code> that accepts a callback, which is invoked with an error if there is one.</p>
  
  <p><code>a</code> is invoked in an Express route request. If there is an error, the error should be the response of the request.</p>
  
  <pre><code>function a(cb) {
    cb(new Error('Some error message'))
  }
  
  app.get('/', function (req, res) {
    a(function (error) {
      if (error) {
        res.json(error, 400)
      }
      res.send('No error')
    })
  })
  </code></pre>
  
  <p>I have looked into the code for Express, and it appears that <code>res.json</code> will stringify my <code>error</code>. However, the result of this is an empty string:</p>
  
  <pre><code>&gt; var e = new Error('Some error message')
  undefined
  &gt; JSON.stringify(e)
  '{}'
  &gt; e.message
  'Some error message'
  </code></pre>
  
  <p>There are ways I could get my route to return the error message here, such as converting the error object <code>toString</code> in my route. However, I would like to know what the best practice is for formatting error messages in Node APIs, and whether that changes things here. Should I format my error messages differently, or should I just handle the <code>Error</code> object in the route, such as:</p>
  
  <pre><code>res.json({ error: error.message }, 400)
  </code></pre>