[英]Catch NameError and NoMethodError with rescue_from in Rails 3
I have this ApplicationController : 我有这个ApplicationController :
class ApplicationController < ActionController::Base
before_filter :class_breadcrumb
end
I require every controller to define its own class_breadcrumb() method. 我要求每个控制器定义自己的class_breadcrumb()方法。 And I'd like to show a message, without raising an exception, if that method doesn't exist.
如果不存在该方法,我想显示一条消息,而不会引发异常。 Finally, I want every other exception to fallback to the standard xml 500 page.
最后,我希望所有其他异常回退到标准xml 500页面。
I felt it would be pretty simple to handle with this rescue_from block: 我觉得使用此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
And it works! 而且有效! But when any other exception raises from within a controller... let's suppose I'm calling an undefined method like this:
但是,当从控制器内部引发任何其他异常时,让我们假设我正在调用一个未定义的方法,如下所示:
<%= undefined_method_that_raise_an_exception %>
I see a blank page with this message: 我看到一个空白页面,显示以下消息:
Internal Server Error
内部服务器错误
no implicit conversion of NameError into String
没有将NameError隐式转换为String
What's wrong with my code? 我的代码有什么问题?
Finally, I figured it out! 终于,我明白了!
# 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
This is metaprogramming Ruby! 这是Ruby的元编程! That's why I've just convinced myself to buy this book and get the pain out: http://pragprog.com/book/ppmetr/metaprogramming-ruby
这就是为什么我刚刚说服自己购买了这本书并减轻了痛苦: http : //pragprog.com/book/ppmetr/metaprogramming-ruby
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.