在许多情况下,人们希望有单独的错误页面,但在我的情况下,我希望在我的主页上有一个自定义错误页面。
我找到了链接 http://makandracards.com/makandra/12807-custom-error-pages-in-rails-3-2这有助于制作单独的错误页面。
最佳答案
我在这方面做了很多工作,并创建了一个 gem called exceptions_handler
让人们更容易使用
可以看个不错的教程here :
我还写了一个详尽的答案here
--
exceptions_app
使用您自己的错误页面的底线是使用 exceptions_app
捕获错误。 Rails 中的中间件 Hook :
config.exceptions_app
sets the exceptions application invoked by theShowExceptionmiddleware
when an exception happens. Defaults toActionDispatch::PublicExceptions.new(Rails.public_path)
.
正如第一个答案已发布,您应该将此应用于您的
config/application.rb
,但我不同意直接将请求发送到路由文件--
Controller
更好的方法是将请求发送到 Controller 操作(我们使用
exceptions#show
):#config/application.rb
config.exceptions_app = ->(env) { ExceptionController.action(:show).call(env) }
#app/controllers/exception_controller.rb
class ExceptionController < ActionController::Base
#Response
respond_to :html, :xml, :json
#Dependencies
before_action :status
def show
render "index"
end
private
def status
@exception = env['action_dispatch.exception']
@status = ActionDispatch::ExceptionWrapper.new(env, @exception).status_code
@response = ActionDispatch::ExceptionWrapper.rescue_responses[@exception.class.name]
end
end
--
浏览量
这将允许您创建以下 View :
#app/views/application/index.html.erb
<% render partial: "errors" if @status.present? %>
关于ruby-on-rails - 在主页上创建自定义 Rails 错误部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24258929/