This post will cover WordPress but the idea can be adapted to different platforms.
The main idea is that when (not if) your database stops working to have a plan B and not to show an ugly message
such as "Error establishing a database connection".

Here is how the default error looks like.

wp-error-establishing-a-database-connection

The database can stop working for many reasons for example

  • you've reached your limits
  • your server ran out of memory and the system had to stop the MySQL process
  • Low disk space
  • MySQL restart
  • etc.

When there is a database error WordPress will look for a file called db-error.php in your wp-content folder.
If it exists there it will be called. That's where we can add our logic to take care of database issues and possibly send an alert to us.

how-to-fail-gracefully-when-the-database-is-gone-away-example-db-error

This script check is there is a cached version (created by WP Super Cache) of the page. If it exists it will be served otherwise a generic message will be shown.
Next, an alert will be sent. Alerts are limited to 3 but this can be changed by editing the file.

Here is how the error message will look like if no cache is found.

wp-error-establishing-a-database-connection-missing-cache

Issues/Suggestions

Submit them here: https://github.com/orbisius/graceful-db-failure/issues

 

Download

Project's page on github: https://github.com/orbisius/graceful-db-failure

Related

 

Disclaimer: The content in this post is for educational purposes only. Always remember to take a backup before doing any of the suggested steps just to be on the safe side.
Referral Note: When you purchase through a referral link (if any) on this page, we may earn a commission.
If you're feeling thankful, you can buy me a coffee or a beer