views:

24

answers:

1

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

+3  A: 

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.

cwninja
No need to do it as a Rack middleware. A plain rescue_from in ApplicationController will do too, and from there, you'll have access to all of ActionController / ActionView to render an interesting page for your users.
François Beausoleil
Thanks! I'm not sure why I didn't think of that!
arfon
That won't work. `ActiveRecord::ConnectionAdapters::ConnectionManagement` happens outside of ActionController::Dispatcher, and raises an exception only handleable by another middleware or a middleware.
cwninja