Displaying errors with node.js Displaying errors with node.js mongoose mongoose

Displaying errors with node.js


There is an error displaying middleware in express. Put it after your router.

app.use(express.errorHandler({ dumpExceptions: true }));

You can use it by calling next() within your route

app.get('/user/:userId', function(req, res, next){  User.get(req.params.userId, function(err, user){    if (err) return next(err);    res.send('user ' + user.name);  });}); 


You could use alternative routes if connection error occured, so it won't be neccessary to perfom connection checks in every request handler.

function connect() {  mongoose.connect(connStr, function(err) {    if (err) {      // all GET requests will end with error message      app.get('*', function(req, res) {        res.end('DB error');      });      // handle errors, retry connection attempt or something...      app.listen(...);      return;    }    // Routes    app.get('/', index.index);    //... And so on    app.listen(...);  };}var app = express.createServer();connect();

You should however find a way to drop route '*' when your connection will be up.


You can set a global variable from the block

mongoose.connect('mongodb://localhost/test', function(err) {    if (err) {        //response.send('Temporary problem', 500);     }});

If this global variable is true/false/..., the act accordingly in your route method.

Not the prettiest approach, but it'll work and is easy to implement.