Reputation: 968
simple code:
in initdb.js
var mongo = require('mongodb'),
MongoClient = mongo.MongoClient,
MongoServer = mongo.Server;
var mongoClient = new MongoClient(new MongoServer('host',port));
var db = mongoClient.db('db');
mongoClient.open(function (err, mongoclient) {
if (err) throw err;
});
If this code throws error, it would not be caught here main.js
app.use(function(err, req, res, next){
console.log('error here');
});
As a result I have errors and crashed app. I just want my app not crash. Any solutions?
Upvotes: 0
Views: 458
Reputation: 8146
It looks like your initdb.js
is run once when your app starts up, not on every request. This makes sense, you probably don't want a new database connection for every request.
However, app.use(function(...
is for code that handles requests. It doesn't run when your app starts up, it runs on every request you get. Or, in this case, just runs when those requests throw errors. (I'm assuming you're using connect/express here.)
So the discrepancy is that your database connection code runs outside of the app.use()
chain, and probaby before the first request ever happens.
In general, if you can't connect to a database, a quick failure is not a bad choice, so I would say your code is OK as is. If you want the server to continue running without the database, then change init.js
from
if (err) throw err;
to
if (err) console.error('error connecting to database', err);
You can get fancy and add some retry logic if you want, but that should be enough to keep your app from crashing immediately. (You may also have to update other parts of your app to work without a database.)
Upvotes: 1