What's the right way to create error messages that get returned in an Express request? What's the right way to create error messages that get returned in an Express request? express express

What's the right way to create error messages that get returned in an Express request?


To add to @steveukx's answer, you can specify an error handler in express, by .useing a function with arity of four.

app.use(function(err, req, res, next){  res.json(500, {    error: err.message  });});

Which will be called whenever you do next(err).See the docs.


I don't now what your response look like, when no error occurs, but this is how I usually handle JSON responses:

function (err, data) {    if (err) {        res.json({            success: false,            error: err.message        }, 400);    }    else {        res.json({            success: true,            data: data        });    }}

Try to wrap this in a extra middleware/function. Keep the signature of the functions similar to standard node style. (First parameter error, following parameter the actual data.) This way it is much easy for the client to process you responses, because all you have to do is look into the success field.


Express routes can use a third argument next that can be used to either skip the current route by just calling next(), or to pass on errors by calling next(err).

Try using:

app.get('/', function (req, res, next) {  a(function (error) {    if (error) {      next(error);    }    else {      res.send('No error')    }  });});

For more information, check out http://expressjs.com/api.html#app.param