ruby-on-rails Rails rescue_from处理程序函数最后被调用

ef1yzkbh  于 2023-08-08  发布在  Ruby
关注(0)|答案(3)|浏览(131)

我有一个Rails 6应用程序

class PostsController
  rescue_from MyException, :handle_my_exception
  around_action :my_around_action

  def create
    Rails.logger.info "Executing create code"
    raise MyException.new("Error Message!")
  end

  def my_around_action
    Rails.logger.info "Executing my_around_action"
    yield
  ensure
    Rails.logger.info "Inside ensure block of my_around_action"
  end

  def handle_my_exception(e)
    Rails.logger.info "Inside Handle My Exception"
  end
end

字符串
调用createaction后,我得到如下顺序的输出

Executing my_around_action
Executing create code
Inside ensure block of my_around_action
Inside Handle My Exception


但我希望按这个顺序输出。

Executing my_around_action
Executing create code
Inside Handle My Exception
Inside ensure block of my_around_action


我该怎么办?我必须用救援工具来做干燥的用途。下面是我试图克服的问题,但我正在寻找解决它使用rescue_from.

class PostsController
  # rescue_from MyException, :handle_my_exception
  around_action :my_around_action

  def create
    Rails.logger.info "Executing create code"
    raise MyException.new("Error Message!")
  rescue MyException => e
    handle_my_exception(e)
  end

  def my_around_action
    Rails.logger.info "Executing my_around_action"
    yield
  ensure
    Rails.logger.info "Inside ensure block of my_around_action"
  end

  def handle_my_exception(e)
    Rails.logger.info "Inside Handle My Exception"
  end
end


当我手动处理异常时,它会以正确的顺序输出,但当我尝试使用rescue_from时,它不会以正确的顺序输出。

vyswwuz2

vyswwuz21#

只需将rescue放入around handler中:

def my_around_action
  Rails.logger.info "Executing my_around_action"
  yield
rescue MyException => e
  handle_my_exception e
ensure
  Rails.logger.info "Inside ensure block of my_around_action"
end

字符串

wqlqzqxt

wqlqzqxt2#

您的解决方案正是您在陈述时所要求的:“但我想要按这个顺序输出."。当然,这是一个很好的解决方案,甚至比rescue_from更好。

xwbd5t1u

xwbd5t1u3#

从确保代码块中取出代码并将其 Package 到lambda中怎么样?MyException可以更改一点,以便稍后可以使用$!handle_my_exception方法中存储lambda访问它

class MyException < Exception
  def initialize(message, ensure_lambda = nil)
    @ensure_lambda = ensure_lambda
    super(message)
  end

  attr_accessor :ensure_lambda
end

个字符

相关问题