Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically handle missing database connection in ActiveRecord?

With the launch of Amazon's Relational Database Service today and their 'enforced' maintenance windows I wondered if anyone has any solutions for handling a missing database connection in Rails.

Ideally I'd like to be able to automatically present a maintenance page to visitors if the database connection disappears (i.e. Amazon are doing their maintenance) - has anyone ever done anything like this?

Cheers Arfon

like image 370
arfon Avatar asked Aug 30 '26 01:08

arfon


1 Answers

You can do this with a Rack Middleware:

class RescueFromNoDB < Struct.new(:app)
  def call(env)
    app.call(env)
  rescue Mysql::Error => e
    if e.message =~ /Can't connect to/
      [500, {"Content-Type" => "text/plain"}, ["Can't get to the DB server right now."]]
    else
      raise
    end
  end
end

Obviously you can customize the error message, and the e.message =~ /Can't connect to/ bit may just be paranoia, almost all other SQL errors should be caught inside ActionController::Dispatcher.

like image 190
cwninja Avatar answered Aug 31 '26 16:08

cwninja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!