Reputation: 471
I have multiple websites transmitting data to my server which in turn writes data to our mongo database. If the server cannot connect to the database, the server becomes useless.
Currently, if a server cannot connect to the database, I am simply logging the error.
mongoose.connection
.once('open', () => { console.log('connected to database'); })
.on('error', () => { console.log('database connection error'); });
My question is, what is best practice if a node server cannot connect to the database? Should I throw the error? Maybe shut down the server completely?
Upvotes: 1
Views: 186
Reputation: 15760
I'm assuming that the server you're talking about serves an API of some sort that the clients are connecting to.
If that server cannot talk to the database, that sounds like a serious issue. You will need to do a couple of things:
The server needs to inform the clients that there's an issue. Hopefully your clients are written in such a way that they will gracefully handle this.
Your server needs to log the details. Not just a message that says "database connection error", but all the error information. You won't be able to troubleshoot without the details.
You probably need some sort of system to notify the system administrator in real time when the database goes down. This is crucial to getting the system back up and running as quickly as possible.
It's difficult to answer more specifically than this, given the limited information you provided. Much of it will be specific to your server implementation. For example, assuming you've written a RESTful API, the clients should probably be sent an HTTP status code of 500 (internal server error) and some descriptive information. If you've chosen some other API implementation, then your response will differ.
Upvotes: 1