【问题标题】:Rails 4, How to have a callback to a custom error?Rails 4,如何回调自定义错误?
【发布时间】:2013-11-06 16:19:49
【问题描述】:

以下是一些 sudo 代码:

exceptions.rb

module Exceptions
  class CriticalError < StandardError
    # Question: How do I attach a callback to this error? Whenever this error is raised, I also want it to ping_me() as a after callback
    def ping_me()
      ...
    end
  end
end

期望的结果:

raise Exceptions::CriticalError # after a callback to this error being raised, it will run the ping_me() method

问题:

如何在 Rails 中执行此操作?我看到了一个rescue_from 方法,但我认为它只能在控制器内部使用

非常感谢!

【问题讨论】:

  • 不清楚你在问什么。您是在问如何拯救和重新抛出异常?你问如何使用pagerduty ping 你?还是别的什么?
  • 我在问如何使用自定义错误执行此操作。例如,现在的代码会引发错误,仅此而已。如何使它自动挽救错误

标签: ruby-on-rails custom-errors custom-error-handling


【解决方案1】:

好的,我想通了

module Exceptions
  class CriticalError < StandardError
    def initialize(error_message)
      ping_me()
      super(error_message)
    end

    def ping_me()
      ....
    end
  end
end


raise Exceptions::CriticalError.new("something went wrong!")

【讨论】:

  • 您想要的与抢救错误无关。如果这个答案真的对你有用,那么你所做的就是在创建对象时调用一个方法。您甚至不需要 raise 关键字。您只需Exceptions::CriticalError.new('foo')
猜你喜欢
  • 2014-07-23
  • 1970-01-01
  • 2014-11-29
  • 2017-07-02
  • 1970-01-01
  • 2015-03-27
  • 2013-09-06
  • 2015-01-11
  • 1970-01-01
相关资源
最近更新 更多