【问题标题】:Error traces in ErubisErubis 中的错误跟踪
【发布时间】:2011-06-30 05:03:33
【问题描述】:

默认情况下,当 Erubis 模板引发错误时,您会得到如下信息:

(erubis):32:in `evaluate': compile error (SyntaxError)
(erubis):30: syntax error, unexpected ')', expecting ']'
(erubis):32: unterminated string meets end of file

行号参考模板。

当您只有一个模板时,这一切都很好,但我正在批处理一堆模板文件。用更有用的错误消息替换上述内容的最佳方法是什么,例如显示源文件路径而不是(erubis):32?

我曾想过拯救、处理异常对象并再次引发,但我想知道 Erubis API(或其他一些)是否提供了更简单的方法。

【问题讨论】:

    标签: ruby erb erubis


    【解决方案1】:

    您可以将 :filename 参数传递给 Erubis。

    eruby = Erubis::Eruby.new(string, :filename=>"file.rhtml")
    

    【讨论】:

    • 请注意,“文件名”可以是任何你想要的。例如,我正在使用一个在数据库中有一些 Erb 模板的系统。在这种情况下,您可以将文件名设为“templates_table_row_#{row.id}”或任何看起来有用的名称。堆栈跟踪可能会显示“RuntimeError: esplosion!\ntemplates_table_row_5:2”
    【解决方案2】:

    我仍然怀疑使用 Erubis API 可能有更好的方法来执行此操作,但这里有一些我编写的似乎可以工作的代码:

    def compile_template(template_path, template_str, context, &block)
      begin
        Erubis::Eruby.new(template_str).evaluate(context, &block)
      rescue Exception => exc
        trace_normalizer = lambda { |line| line.gsub(/^\(erubis\):/, template_path + ':') }
        backtrace = exc.backtrace.collect(&trace_normalizer)
        message = trace_normalizer.call(exc.message)
        raise exc.class, message, backtrace
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2013-01-02
      • 1970-01-01
      • 2015-03-15
      • 2015-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多