使用方法如下:
rescue_from(*klasses, &block)
它的第一个参数是出错的类型集合,可以指定多个错误类型或者出错信息,每一项都会调用klass.is_a?(klass);第二个参数是可以带一个block,我们可以使用with来指定:
出错处理是可以继承的,比如底下代码中,如果没有指定错误处理类型的话,就会调同rescue_from ‘MyAppError::Base’的出错处理;
ApplicationController:
1 2 3 4 5 6 7 8 9 10
| 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
|
现在的项目这么写的。捕获Rails 404 error ,跳转到/public/404.html
application_controller:
1 2 3 4 5 6 7 8 9
| rescue_from ActionController::UnknownFormat, ActionController::RoutingError, ActionController::UnknownController, ActiveRecord::RecordNotFound, with: :render_not_found
def render_not_found redirect_to not_found_url end
|
routes.rb:
1
| get 'not_found' => 'home#not_found'
|
home_controller:
1 2 3 4 5 6
| def not_found respond_to do |format| format.html { render file: "#{Rails.root}/public/404.html", layout: false, status: 404} format.all { render :nothing => true, :status => status } end end
|
action_controller:
1
| return redirect_to not_found_path unless @product
|