rescue_from ::AbstractController::ActionNotFound不起作用

9

I have the following code:

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):
4个回答

7

这个类似的问题表明你不再能捕获ActionNotFound异常。查看该链接以获取解决方法。这个建议使用Rack中间件来捕获404错误,在我看来是最干净的方法。


3
为了在控制器中解决 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::Baseprocess方法,该方法会抛出AbstractController::ActionNotFound异常(参见源代码)。


0

0

我认为我们应该在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 在你的Rails应用程序中处理异常


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接