有没有办法告诉 Rails 呈现您的自定义错误页面(例如,您在ErrorsController
. 我搜索了很多主题,其中一个似乎有点工作的主题是添加到您的ApplicationController
类似
if Rails.env.production?
rescue_from Exception, :with => :render_error
rescue_from ActiveRecord::RecordNotFound, :with => :render_not_found
rescue_from ActionController::UnknownController, :with => :render_not_found
rescue_from ActionController::UnknownAction, :with => :render_not_found
end
然后你写你的方法render_error
和render_not_found
你想要的方式。在我看来,这似乎是一个非常不雅的解决方案。此外,这很糟糕,因为您必须确切知道可能发生的所有错误。这是一个临时解决方案。
此外,真的没有简单的方法来拯救ActionController::RoutingError
那种方式。我看到一种方法是添加类似
get "*not_found", :to => "errors#not_found"
到你的routes.rb
. ActionController::RoutingError
但是,如果您想手动提高某个地方怎么办?例如,如果一个不是管理员的人试图通过猜测 URL 来访问“管理”控制器。在这些情况下,我更喜欢引发 404,而不是引发某种“未经授权的访问”错误,因为这实际上会告诉人们他猜到了 URL。如果你手动提升它,它会尝试渲染一个 500 的页面,我想要一个 404。
那么有没有办法告诉 Rails:“在所有情况下,您通常会渲染 a404.html
或 a 500.html
,渲染我的自定义 404 和 500 页面”?(当然,我从文件夹中删除了404.html
和500.html
页面public
。)