繁体   English   中英

在Rails 3中使用rescue_from捕获NameError和NoMethodError

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM