【问题标题】:How to use rails rescue_from outside the controller如何在控制器外部使用 rails rescue_from
【发布时间】:2022-01-19 15:40:28
【问题描述】:
  • 我正在使用 GrapeApi 并且我正在使用服务设计模式,因此我需要处理控制器外部的异常,但 rescue_from 仅在控制器内部工作。 - 我几乎在所有方法中都使用rescue ExceptionName,但我发现我不遵守 DRY 规则。所以我创建了一个文件services/exception_handler_service.rb。并尝试了include ActiveSupport::Rescuable,它只是被忽略了,extend ActiveSupport::Rescuable 并抛出未定义的方法rescue_from。

有没有办法在控制器外部使用rescue_from?

【问题讨论】:

  • 通常,控制器也应该能够从模型和服务对象中的异常中拯救出来,因为控制器是调用模型和视图的实例。您能否详细说明您的设置以及为什么某些异常在您的控制器中无法挽救。

标签: ruby-on-rails ruby exception rescue


【解决方案1】:

这里是使用 rescue_with_handler 的简单 Ruby 示例

require 'active_support/rescuable'


class MyError < StandardError
end

class MyClass
  include ActiveSupport::Rescuable

  rescue_from MyError, with: :catch_error

  def method_with_error
    raise MyError
    puts "I am after error"
  rescue MyError => e
    rescue_with_handler(e)
  end

  private

  def catch_error
    puts "Catch error"
  end
end

MyClass.new.method_with_error # will print Catch error

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多