我每次在Rails 3上获得异常时都可以执行一个方法吗?

时间:2011-08-17 02:13:16

标签: ruby-on-rails ruby ruby-on-rails-3

我几乎尝试了网上的所有内容,我想要的只是在出现“ActiveRecord :: RecordNotFound”或“No route matches”等异常时调用方法。

ApplicationController的救援不起作用,但为什么?

class ApplicationController < ActionController::Base
  protect_from_forgery

  private
    def self.send_report_error(message)
      Notifier.page_failure(message).deliver
    end

rescue ActiveRecord::RecordNotFound
  # handle not found error
  send_report_error ActiveRecord::RecordNotFound.to_s
rescue ActiveRecord::ActiveRecordError
  # handle other ActiveRecord errors
  send_report_error ActiveRecord::ActiveRecordError.to_s
rescue # StandardError
  # handle most other errors
  send_report_error "common error"
rescue Exception
  # handle everything else
  send_report_error "common exception"
end

1 个答案:

答案 0 :(得分:12)

使用rescue_from。例如:

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, :with => :send_report_error
end

http://api.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html