2014-06-17 24 views

回答

0

所以我做了以下方法,幫助這個:

的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> 
2

我已經在這個廣泛的合作,並創建了一個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? %>