开发者

Can I execute a method everytime I get an exception on Rails 3?

I tried almost everything on web, all I want is to call a method whenever an exception like "ActiveRecord::RecordNotFound" or "No route matches" appears.

Rescues from ApplicationController does not work, but why?

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


Use rescue_from. For example:

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜