ruby-on-rails - 在主页上创建自定义 Rails 错误部分

标签 ruby-on-rails ruby-on-rails-3 error-handling

在许多情况下,人们希望有单独的错误页面,但在我的情况下,我希望在我的主页上有一个自定义错误页面。

我找到了链接 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 the ShowExceptionmiddleware when an exception happens. Defaults to ActionDispatch::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/

相关文章:

mysql - Rails 的 update_all 方法将错误的时间保存到 MySQL DB 中

ruby-on-rails - 在 rails 3.2 + 设计 2.0 之后设计列confirmed_at 不再更新

ruby - 导轨 : How to determine size of http response the server delivers to the client?

go - 合并多个错误字符串

jquery - 如何将数据从 Controller 发送到 ruby​​ 中的 View

android - 与网络同步的应用程序

ruby-on-rails - Rails sanitize 删除默认允许的标签

php - 在 PHP 7 中触发 fatal error (非异常)

ruby-on-rails - 为什么在某些情况下 Rails 应用返回 406 而不是 404?

ruby-on-rails - 事件管理员 : Customize only new form