少於 1 分鐘閱讀

本文使用 Ruby 2.3.1 / Rails 5.0.0

前言

通常我們會使用預設放在public裡面的404及500頁面來建立,但其風格跟自己網頁差太多,不好跟自己現有載入的css同步 因此本文將介紹該如何拉出來自己定義,並可以直接套layout的風格。 本文重點:

  • 建立errors專用的controller
  • 設定route
  • 告訴rails我們要自定義頁面
  • 測試的方式

##動態顯示404、500頁面

###1) 建立controller

$ rails generate controller errors not_found internal_server_error

###2) 調整controller

class ErrorsController < ApplicationController
  def not_found
    render(:status => 404)
  end

  def internal_server_error
    render(:status => 500)
  end
end

###3) 設定route

match "/404", :to => "errors#not_found", :via => :all
match "/500", :to => "errors#internal_server_error", :via => :all

###4) 告訴rails我們要自己處理錯誤頁面

# [path] config/application.rb
config.exceptions_app = self.routes

###5) 刪除原本的public下的404及500網頁

rm public/{404,500}.html

###6) 調整你的View

  • not_found.html.erb
  • internal_server_error.html.erb

一般來說他們會被render在layout/application.html.erb之中 照慣例,你也可以自行建立一個專用的layout/error.html.erb來統一錯誤訊息的版型

###7) 進行測試 你可以使用 http://localhost:3000/404 或 http://localhost:3000/500 來測試

其它頁面若也想測試的話,可以在developmant.rb把錯誤訊息先暫時關閉

# [path] config/environments/development.rb
config.consider_all_requests_local = false

更新時間:

留言