Rails 动态错误页面(404、422、500)显示为空白

Rails dynamic error pages (404, 422, 500) showing as blank

我正在将动态错误页面实现到一个应用程序中,感觉它正在 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 => "errors#not_found",但具有讽刺意味的是,它没有找到 /404 的路由(不,不仅如此 :)).

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

好像有些设置不对。 在你的路线中试试这个:

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

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

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

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

改为这样做:

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

然后您将需要视图,显然 ;) 不要忘记也删除 public 目录中的错误页面。