2

默认情况下,当 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(或其他一些)是否提供了一种更简单的方法。

4

2 回答 2

2

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

eruby = Erubis::Eruby.new(string, :filename=>"file.rhtml")
于 2011-02-23T11:39:33.710 回答
0

我仍然怀疑使用 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
于 2011-02-19T02:15:14.523 回答