本篇的作法是我參考了文末的 reference 後融合而成。

在 app/controllers/application_controller.rb ,首先在最前面加上

unless Rails.env == 'development'
  rescue_from Exception, :with => :render_500 
  rescue_from RuntimeError, :with => :render_500
  rescue_from ActiveRecord::RecordNotFound, :with => :render_404
end

然後定義 render_404 、 render_500 、 render_optional_error_file 這三個 method

def render_404
  render_optional_error_file(404)
end

def render_500
  render_optional_error_file(500)
end

def render_optional_error_file(status_code)
  status = status_code.to_s
  if ["404", "422", "500"].include?(status)
    render :template => "/errors/#{status}.html.erb", :status => status, :layout => "errors"
  else
    render :template => "/errors/unknown.html.erb", :status => status, :layout => "errors"
  end
end

打開 config/routes.rb ,寫上所有找不到頁面要處理 404 的 route

match "*other", :to => "welcome#handle404"

在 app/controllers/welcome_controller.rb 加上 handle404 action

def handle404
  render_404
end

最後把 /public/404.html, 422.html, 500.html 刪除,這樣就完成了!

 

Reference:
render_optional_error_file method
rails3定制404和500错误

Extra:
另外我後來還有找到 gem 可以處理 errors 頁面,但因為那時候 code 都寫完了所以沒有測,僅列出文章和連結提供參考
Helder Ribeiro — Dynamic Error Pages in Rails 3 with Goalie
wrangler gem
dynamic_errors gem

arrow
arrow

    笨笨小蟹 發表在 痞客邦 留言(1) 人氣()