I have a function called a
that accepts a callback, which is invoked with an error if there is one.
a
is invoked in an Express route request. If there is an error, the error should be the response of the request.
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')
})
})
I have looked into the code for Express, and it appears that res.json
will stringify my error
. However, the result of this is an empty string:
> var e = new Error('Some error message')
undefined
> JSON.stringify(e)
'{}'
> e.message
'Some error message'
There are ways I could get my route to return the error message here, such as converting the error object toString
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 Error
object in the route, such as:
res.json({ error: error.message }, 400)