简体   繁体   English

Rails rescue_from停止执行流程

[英]Rails rescue_from stops execution flow

I'm having problems using the rescue_from 我在使用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

In this code as you can see I simply raise an exception before the action starts, that is caught by the rescue_exception method. 在这段代码中你可以看到我只是在动作开始之前引发一个异常,它被rescue_exception方法捕获。 The problem is that after I catch the exception the application flow stops and the action code is never reached. 问题是,在我捕获异常后,应用程序流停止并且永远不会到达操作代码。 Is it possible to continue the execution after the exception is rescued? 在拯救例外后是否可以继续执行?

Short answer, no. 简短的回答,没有。 rescue_from is intended to handle exceptions that are otherwise uncaught. rescue_from旨在处理未被捕获的异常。

If you want to catch a particular exception for every action in a controller, I would recommend an around_action . 如果你想为控制器中的每个动作捕获一个特定的异常,我会推荐一个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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM