加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 我每次在Rails 3上获得异常时都可以执行一个方

发布时间:2020-12-17 01:45:32 所属栏目:百科 来源:网络整理
导读:我几乎尝试了网上的所有内容,我想要的只是在出现“ActiveRecord :: RecordNotFound”或“No route matches”这样的异常时调用方法. ApplicationController的救援工作不起作用,但为什么呢? class ApplicationController ActionController::Base protect_from
我几乎尝试了网上的所有内容,我想要的只是在出现“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

解决方法

使用rescue_from.例如:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读