Error traces in Erubis
By default, when an an Erubis template raises an error, you get something like this:
(erubis):32:in `evaluate': compile error (SyntaxError)
(erubis):30: syntax error, unexpected ')', expecting ']'
(erubis):32: unterminated string meets end of file
The line numbers refer to the template.
That's all well and good when you just have one template, but I'm batch-processing a bunch of template files. What's the bes开发者_开发百科t way to replace the above with a more usable error message, e.g. one that shows the path to the source file instead of (erubis):32
?
I'd thought of rescuing, messing around with the exception object, and raising again, but I'm wondering if there's an easier way provided by the Erubis API (or some other one).
You can pass :filename parameter to Erubis.
eruby = Erubis::Eruby.new(string, :filename=>"file.rhtml")
I still suspect there might be a better way to do this using the Erubis API, but here's some code I wrote that seems to work:
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
精彩评论