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

Dgl*_*mut 3 ruby ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)

dna*_*oli 12

使用rescue_from.例如:

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, :with => :send_report_error
end
Run Code Online (Sandbox Code Playgroud)

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