在很多情況下,人們希望有單獨的錯誤頁面,但在我的情況下,我想在我的主頁上創建一個自定義錯誤頁面。在主頁上創建自定義Rails錯誤部分
我發現鏈接http://makandracards.com/makandra/12807-custom-error-pages-in-rails-3-2這有助於製作單獨的錯誤頁面。
在很多情況下,人們希望有單獨的錯誤頁面,但在我的情況下,我想在我的主頁上創建一個自定義錯誤頁面。在主頁上創建自定義Rails錯誤部分
我發現鏈接http://makandracards.com/makandra/12807-custom-error-pages-in-rails-3-2這有助於製作單獨的錯誤頁面。
所以我做了以下方法,幫助這個:
的routes.rb:
match '/404', :to => 'home#not_found'
match '/422', :to => 'home#rejected'
match '/500', :to => 'home#server_error'
application.rb中
config.exceptions_app = self.routes
Home_controller.rb
def not_found
@errors = I18n.t("home.errors.error_404")
render 'index'
end
def rejected
@errors = I18n.t("home.errors.error_422")
render 'index'
end
def server_error
@errors = I18n.t("home.errors.error_500")
render 'index'
end
在我家/索引頁:
<%= render :partial => 'errors', :errors => @errors %>
和一個簡單的局部_errors:
<div class="row">
<% if @errors %>
<div class="alert alert-wide alert-info">
<p style="display:inline"><%= @errors %></p>
</div>
<% end %>
</div>
我已經在這個廣泛的合作,並創建了一個gem called exceptions_handler
讓人們更容易使用
您可以看到一個很好的教程here:
我也寫一個詳盡的答案here
-
exceptions_app
與自己的錯誤頁面的底線是用來捕獲錯誤exceptions_app
Rails中的中間件鉤子:
config.exceptions_app
設置發生異常時由ShowExceptionmiddleware
調用的例外應用程序。默認爲ActionDispatch::PublicExceptions.new(Rails.public_path)
。
作爲第一個答案已經發布,你應該將此您config/application.rb
,但我會發送請求不同意路由文件直接
-
控制器
更好的方法是將請求發送到控制器操作(我們使用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
-
查看
這將允許您創建以下觀點:
#app/views/application/index.html.erb
<% render partial: "errors" if @status.present? %>