【问题标题】:Rails dynamic error pages (404, 422, 500) showing as blankRails 动态错误页面(404、422、500)显示为空白
【发布时间】:2016-01-13 23:54:20
【问题描述】:

我正在将动态错误页面实现到应用程序中,并且感觉它在 public 文件夹中查找(现在不存在的)模板,而不是遵循我设置的路线。

config/application.rb 中,我添加了config.exceptions_app = self.routes 行来说明这一点。

然后我将以下内容添加到我的路线中:

get "/not-found", :to => "errors#not_found"
get "/unacceptable", :to => "errors#unacceptable"
get "/internal-error", :to => "errors#internal_error"

错误控制器如下所示:

class ErrorsController < ApplicationController
  layout 'errors'
  def not_found
    render :status => 404
  end

  def unacceptable
    render :status => 422
  end

  def internal_error
    render :status => 500
  end
end

转到/not-found 会显示应有的模板,但访问任何不存在的 URL(即 /i-dont-exist)会呈现一个空白页面。

我能看到的唯一原因是异常处理需要路由,例如,get "/404", :to =&gt; "errors#not_found",但具有讽刺意味的是,它没有找到 /404 的路由(不,不仅仅是它工作:))。

任何建议,不胜感激。谢谢,史蒂夫。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 configuration routing


    【解决方案1】:

    似乎有些设置是错误的。 在你的路线中试试这个:

    match '/404', to: 'errors#not_found', via: :all(匹配而不是获取)

    您提到在application.rb 中有config.exceptions_app = self.routes,这很好。但请确保在测试更改之前重新启动服务器。

    并确保您的错误视图文件与ErrorsController 中的操作同名。

    如果您在控制台中遇到任何类型的(哈哈)错误,您可以发布吗?

    【讨论】:

    • match 做到了 - 我不确定为什么,但是让路由响应所有方法是让它触发所需的全部。其他一切都连接得很好。感谢普斯的帮助!
    【解决方案2】:

    改为这样做:

    routes.rb

    %w(404 422 500).each do |code|
      get code, :to => "errors#show", :code => code
    end
    

    errors_controller.rb

    class ErrorsController < ApplicationController
      def show
        render status_code.to_s, :status => status_code
      end
    
      protected
      def status_code
        params[:code] || 500
      end
    end
    

    在您的 config/application.rb 中确保您有:

    module YourWebsite
      class Application < Rails::Application
    
        config.exceptions_app = self.routes
        # .. more code ..
      end
    end
    

    那么你显然需要这些视图;)不要忘记删除公共目录中的错误页面。

    【讨论】:

    • 感谢 DaniG2k,一个不错的 RESTful 解决方案。接受的答案对我有用,但这是一个很好的可行选择。感谢您的努力。
    猜你喜欢
    • 1970-01-01
    • 2014-11-10
    • 2014-10-17
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多