自定义404不从控制器触发

时间:2014-05-05 15:52:38

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

我在使用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

1 个答案:

答案 0 :(得分:1)

将路线添加到控制器的此操作:

match 'path' to: 'errors#catch_404'

并创建像这样的错误控制器

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

之后它应该开始工作。