【问题标题】:Custom 404 not firing from controller自定义 404 未从控制器触发
【发布时间】:2014-05-05 15:52:38
【问题描述】:

我正在尝试在使用 cms gem 时处理 404 错误。在我过去的应用程序中,这种 404 方法似乎有效,但现在它无法挽救错误。有什么想法吗?

# application_controller.rb
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  rescue_from ActionController::RoutingError, :with => :render_404

  def after_sign_in_path_for(resource)
    admin_cms_path
  end

private

  def render_404(exception = nil)
    if exception
      logger.info "Rendering 404: #{exception.message}"
    end
    flash[:error] = 'The page you entered is unavailble, please send us an email if this is unexpected'
    redirect_to root_path
  end
end

路线

# routes.rb
Amskier::Application.routes.draw do
  # ...    
  comfy_route :blog_admin,        path: '/admin'
  comfy_route :cms_admin,         path: '/admin'

  root to: "cms/content#show"

  comfy_route :cms,               path: '/', sitemap: false
end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 error-handling http-status-code-404


    【解决方案1】:

    将路由添加到控制器的这个动作中:

    match 'path' to: 'errors#catch_404'
    

    并像这样创建错误控制器

    class ErrorsController < ApplicationController
      def catch_404
        raise ActionController::RoutingError.new(params[:path])
      end
    end
    

    之后它应该开始工作了。

    【讨论】:

    • 在 Rails 3.x.x 中,ApplicationController 无法捕获 ActionController::RoutingError,因此,我们无法像使用 ActiveRecordError::RecordNotFound 那样利用rescue_from。您可以继续使用@Babar 的解决方案。将您的路线放在所有路线的末尾。
    猜你喜欢
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 2017-01-31
    • 1970-01-01
    • 2011-01-05
    相关资源
    最近更新 更多