【问题标题】:rescue_from ::AbstractController::ActionNotFound not workingrescue_from ::AbstractController::ActionNotFound 不工作
【发布时间】:2012-11-17 17:33:17
【问题描述】:

我有以下代码:

unless Rails.application.config.consider_all_requests_local
  rescue_from Exception, with: :render_exception
  rescue_from ActiveRecord::RecordNotFound, with: :render_exception
  rescue_from ActionController::UnknownController, with: :render_exception
  rescue_from ::AbstractController::ActionNotFound, with: :render_exception
  rescue_from ActiveRecord::ActiveRecordError, with: :render_exception
  rescue_from NoMethodError, with: :render_exception
end

它们都完美无缺,除了 ::AbstractController::ActionNotFound

我也试过了

AbstractController::ActionNotFound
ActionController::UnknownAction

错误:

   AbstractController::ActionNotFound (The action 'show' could not be found for ProductsController):

【问题讨论】:

    标签: ruby-on-rails exception ruby-on-rails-3.2 actioncontroller


    【解决方案1】:

    This similar question 表示您无法再捕获ActionNotFound 异常。检查链接以获取解决方法。 This suggestion 使用 Rack 中间件来捕获 404 对我来说看起来最干净。

    【讨论】:

      【解决方案2】:

      要在控制器中拯救AbstractController::ActionNotFound,您可以尝试以下操作:

      class UsersController < ApplicationController
      
        private
      
        def process(action, *args)
          super
        rescue AbstractController::ActionNotFound
          respond_to do |format|
            format.html { render :404, status: :not_found }
            format.all { render nothing: true, status: :not_found }
          end
        end
      
      
        public
      
        # actions must not be private
      
      end
      

      这会覆盖引发AbstractController::ActionNotFoundAbstractController::Baseprocess 方法(请参阅source)。

      【讨论】:

        【解决方案3】:

        我认为我们应该在ApplicationController 中捕获AbstractController::ActionNotFound。我已尝试遵循 似乎无法正常工作

        rescue_from ActionController::ActionNotFound, with: :action_not_found
        

        我在ApplicationController 中找到了更简洁的方法来处理此异常。要在应用程序中处理 ActionNotFound 异常,您必须在应用程序控制器中覆盖 action_missing 方法。

        def action_missing(m, *args, &block)
          Rails.logger.error(m)
          redirect_to not_found_path # update your application 404 path here
        end
        

        解决方案改编自:coderwall handling exceptions in your rails application

        【讨论】:

          【解决方案4】:

          正如 Grégoire 在他的回答中所描述的那样,覆盖 process 似乎有效。但是,Rails 代码说要覆盖process_action。但是,这不起作用,因为process_action 永远不会因为检查process 中的action_name 而被调用。

          https://github.com/rails/rails/blob/v3.2.21/actionpack/lib/abstract_controller/base.rb#L115

          https://github.com/rails/rails/blob/v3.2.21/actionpack/lib/abstract_controller/base.rb#L161

          【讨论】:

            猜你喜欢
            • 2014-08-19
            • 1970-01-01
            • 1970-01-01
            • 2015-02-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-09-22
            相关资源
            最近更新 更多