2013-02-13 34 views
1

使用Rails 3.2.x中和Ruby 1.9.3如何验证ERB或捕捉ERB的SyntaxError

给定一个恶意形成的ERB模板,我该怎么办下列之一:

  • 验证如果是坏的
  • 捕捉当我试图得到一个坏的模板的结果是再培训局抛出的SyntaxError模板,并引发错误。

我认为这会工作:

template = "Hello <%= @planet name %>" 
@planet_name = "Earth" 

begin 
ERB.new(template,nil).result(binding) 
rescue 
Raise StandardError, "Bad Erb template" 
end 

但事实并非如此。相反,我得到ERB一个SyntaxError。

有没有一种方法来捕捉/验证这些错误?

回答

2

具体救援的SyntaxError原来做的伎俩。

begin 
ERB.new(template,nil).result(binding) 
rescue SyntaxError 
raise StandardError, "Bad Erb template" 
end 
+0

无参数的rescue子句捕获StandardError,而SyntaxError不是StandardError的子类。 http://www.ruby-doc.org/core-1.9.3/SyntaxError.html – 2013-02-13 15:23:53