Rails:如果没有可用的数据库连接,则显示维护页面

我正在寻找一种解决方案,当没有可用于连接的Mysql服务器时,我的rails应用程序可以呈现用户友好的维护页面。

通常从active_record中的mysql连接适配器抛出一个Mysql::Error类似于:

 /!\ FAILSAFE /!\ Wed May 26 11:40:14 -0700 2010 Status: 500 Internal Server Error Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock 

是否有一种低开销的方法来捕获此错误并呈现维护页面?

我假设因为连接实际上是在active_record mysql适配器中进行的,所以应用程序在抛出错误之前从未进入控制器堆栈,因此您无法在控制器中捕获它。

任何投入将不胜感激。

您可以在root_path控制器中创建一个视图:

 map.root :controller => "foo", :action => "index" 

假设您将此视图称为“db_maintenance.html.erb”。 在控制器中,执行以下操作:

 def index begin @widgets = Widget.find(:all) rescue Exception => e # This will only happen if DB stuff fails redirect_to :action => "db_maintenance", :error => e.message end end ... def db_maintenance @error = params[:error] # You might want to do something with this here or in the view # renders the app/views/foo/db_maintenance.html.erb view end 

在您看来,您可以使用以下内容:

 

Sorry for the inconvenience

blah blah blah. This happened because of:
<%= @error %>

当然,这只会在用户点击您网站的主页面时有所帮助,但您可以从那里轻松推断出来。 您可以将“def db_maintenance”操作添加到应用程序控制器,并手动指定它应该呈现的视图。 它并不完美,但它应该完成工作。

我认为这是关于您的前端配置。 例如,如果在某些mongrel前面有Apache,则可以通过ErrorDocument指令配置Apache,以便在出现错误时显示合适的文件。

你的前端是什么?

斯蒂芬