【问题标题】:rails 3.2 with jbuilder swallowing errors, instead rendering missing partial带有 jbuilder 吞咽错误的 rails 3.2,而不是呈现丢失的部分
【发布时间】:2015-07-11 21:51:50
【问题描述】:

我正在使用带有 JBuilder 的 Rails 3.2.21。

我有一个示例,我在 js.erb 文件中使用 JBuilder 部分来预填充一些字段:

var orderData = <%= raw render :partial => 'orders/orders', formats: [:json], handlers: [:jbuilder], locals: {orders: @orders} %>;

我有一个奇怪的问题,如果在 jbuilder 模板中抛出错误,它会呈现缺少模板错误。所以

如果 _orders.json.jbuilder 看起来像这样 json.array! orders do |order| json.someProperty order.a_missing_property end

我明白了: ActionView::Template::Error (Missing partial orders/orders with {:locale=>[:en], :formats=>[:js, :html], :handlers=>[:erb, :builder, :coffee, :haml, :jbuilder, :riif]}

但如果没有错误,这会正确呈现。

知道我的错误是如何被吞没的吗?

更新

我在这里创建了一个演示应用程序:https://github.com/earnold/error-demo

如果您加载主页/索引,则会收到缺少模板的错误。如果注释掉模板中的坏行,就可以正常渲染模板。我要做的是确保错误不会被吞下,而是显示在页面上。

【问题讨论】:

    标签: ruby-on-rails json jbuilder


    【解决方案1】:

    我在 Github 上得到了答案:https://github.com/rails/jbuilder/issues/40

    短版:这可以通过猴子修补 Rails 来解决。把它放在一个初始化器中,你就可以开始了。

    if Rails.env.development? || Rails.env.staging?
      module ActionView
        class Template
    
          protected
    
          def handle_render_error(view, e) #:nodoc:
            if e.is_a?(Template::Error)
              e.sub_template_of(self)
              raise e
            else
              assigns  = view.respond_to?(:assigns) ? view.assigns : {}
              template = self
              unless template.source
    
                # If an error occurs while the Jbuilder template is being rendered in
                # in a nested context, you have a mismatch between the template format
                # and the view context. Therefore, this block of code would raise
                # a false exception (ActionView::MissingTemplate) and swallow the original
                # error. This monkey patch tricks rails into thinking it was a json request
                # so that refreshing the source hits the right partial
                if template.formats == [:json]
                  view.lookup_context.formats = [:json]
                end
    
                template = refresh(view)
                template.encode!
              end
              raise Template::Error.new(template, assigns, e)
            end
          end
    
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-25
      • 2016-06-29
      • 2017-01-26
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      • 2011-10-24
      相关资源
      最近更新 更多