Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Displaying errors with node.js

Displaying errors with node.js

Problem

I want to be able to send a friendly Error message to my user whenever I cannot connect to my MongoDB server from inside node.js, instead of just having node.js freaking out as it does right now.

Apparently this won't work as I cannot access the response variable from outside a route method (app.get('/' ...), so what should I do instead?
No need to display something fancy, but just informing the user about a temporary problem would be amazing.

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

// Routes
app.get('/', index.index);
//... And so on
Problem courtesy of: Industrial

Solution

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.

Solution courtesy of: elmigranto

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Displaying errors with node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×