[英]Catch NameError and NoMethodError with rescue_from in Rails 3
我有這個ApplicationController :
class ApplicationController < ActionController::Base
before_filter :class_breadcrumb
end
我要求每個控制器定義自己的class_breadcrumb()方法。 如果不存在該方法,我想顯示一條消息,而不會引發異常。 最后,我希望所有其他異常回退到標准xml 500頁面。
我覺得使用此rescue_from塊將非常簡單:
rescue_from "NameError" do |e|
if e.to_s.include?('class_breadcrumb')
flash.now["alert-danger"] = "You didn't provide a breadcrumb for #{request.fullpath}! Please send us a feedback including this message!"
render params[:action]
else
# default behavior
render :xml => e, :status => 500
end
end
而且有效! 但是,當從控制器內部引發任何其他異常時,讓我們假設我正在調用一個未定義的方法,如下所示:
<%= undefined_method_that_raise_an_exception %>
我看到一個空白頁面,顯示以下消息:
內部服務器錯誤
沒有將NameError隱式轉換為String
我的代碼有什么問題?
終於,我明白了!
# rescue NoMethodError
def method_missing(method, *args, &block)
if method == 'class_breadcrumb'
flash.now["alert-danger"] = "You didn't provide a breadcrumb for #{request.fullpath}! Please send us a feedback including this message!"
render params[:action]
end
end
這是Ruby的元編程! 這就是為什么我剛剛說服自己購買了這本書並減輕了痛苦: http : //pragprog.com/book/ppmetr/metaprogramming-ruby
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.