ITeye博客

Rails3用rescue_from自定义错误页面

iseesea · 2011-01-04 11:29 · Ruby on Rails · 编程语言 · HTML · Ruby · XML · ActiveRecord · Markdown

很早之前我自定义错误页面都是重写Showexceptions的rescue_action_in_public和rescue_action_locally方法,但是这样做侵入性太强,今天偶尔看到了一个方法:rescue_from的方法,使用方法如下; rescue_from(*klasses, &block) 它的第一个参数是出错的类型集合,可以指定多个错误类型或者出错信息,每一项都会调用klass.is_a?(klass);第二个参数是可以带一个block,我们可以使用with来指定: 出错处理是可以继承的,比如底下代码中,如果没有指定错误处理类型的话,就会调同rescue_from 'MyAppError::Base'的出错处理;


class ApplicationController < ActionController::Base
rescue_from ActiveRecord::InvalidForeignKey,ActiveRecord::StatementInvalid , :with => :show_fk_errors

    rescue_from 'MyAppError::Base' do |exception|
      render :xml => exception, :status => 500
    end

  protected

  def show_fk_errors(exception)
    render :template => "/errors/fk_error.html.erb",:object=>@exception = exception
  end
end

PS: 在ruby文件中如果有中文出错的话可以在文件开头添加


#encoding: utf-8
。。。。。。

来指定文件编码,如果还出错的话请人工转码吧。。。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。