title: NodeJS Mongoose handle database connection failed exception
body: <p>I'm building a restful web service api using NodeJS.It uses Mongoose as ODM and using MongoDB for backend.
  Below i will explain my scenario</p>
  
  <p>I started nodejs server
  After that i shutdown the MongoDB database.
  Then call the GET api call,it doest catch any errors and api call get hang.</p>
  
  <p>database config in main.js file</p>
  
  <pre><code>var mongoose = require('mongoose');
  var uri = 'mongodb://localhost/mydb';
  mongoose.Promise = global.Promise;
  var options = { server: {socketOptions: { keepAlive: 300000, connectTimeoutMS: 10000 } } } ;
  mongoose.connect(uri,options);
  var db = mongoose.connection;
  db.on('error',console.log.bind(console,'connection refused !!!!!'));
  db.once('open', console.log.bind(console,'connection success !!!!!'));
  </code></pre>
  
  <p>this is my basic GET call</p>
  
  <pre><code> var express = require('express');
      var router = express.Router();
      var mongoose = require('mongoose');
      var rootRes = require('../model/rootresources.js');
  
      router.get('/', function(req, res, next) {
        rootRes.find({},function (err, rootResource) {
      if (err){
       console.log('Error occurd !!!') }
      res.json(rootResource);
  });
  });
  </code></pre>
  
  <p>Even database connection failed, the code does not goes to error block. So didn't capture the database refuse when database connection is failed in the API call.</p>
  
  <p>I want to capture that error and send internal server error (code:500) to client. I tried to find the solution but still could not find it 
  Any solutions or do i made a mistake ?</p>
  
  <p>Thank you
  Amila</p>