【问题标题】:Rails rescue_from stops execution flowRails rescue_from 停止执行流程
【发布时间】:2015-03-05 08:57:34
【问题描述】:

我在使用 rescue_from 时遇到问题

class SimpleError < StandardError; end

before_action :raise_exception
rescue_from SimpleError, with: :rescue_exception    

def raise_exception
    raise SimpleError
end

def rescue_exception
    log $!
end

def index
    @unreachable_code = true
def

如您所见,在这段代码中,我只是在动作开始之前引发了一个异常,该异常被rescue_exception 方法捕获。问题是,在我捕捉到异常之后,应用程序流程停止并且永远不会到达操作代码。 异常解救后是否可以继续执行?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-4.2


    【解决方案1】:

    简短的回答,不。 rescue_from 旨在处理未捕获的异常。

    如果您想为控制器中的每个操作捕获特定异常,我建议您使用around_action

    class MyController < ApplicationController
      class SimpleError < StandardError; end
    
      around_action :handle_simple_errors
    
      def index
        # code that might raise SimpleError
        @unreachable_code = true
      def
    
      private
    
      def handle_simple_errors
        begin
          yield
        rescue SimpleError
          # handle SimpleError however
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2016-08-29
      • 2018-04-17
      • 1970-01-01
      • 2021-11-30
      • 2016-06-30
      • 2011-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多