为什么这种救援语法有效?

好的,所以我有一个我正在使用的应用程序的方法,它在生产中工作。 我的问题为什么这有效? 这是新的Ruby语法吗?

def edit load_elements(current_user) unless current_user.role?(:admin) respond_to do |format| format.json { render :json => @user } format.xml { render :xml => @user } format.html end rescue ActiveRecord::RecordNotFound respond_to_not_found(:json, :xml, :html) end 

当他们在一个方法中时,不需要将其绑定到显式begin ,这就是定义语法的方式。 例如,请参阅此处的#19和此SO问题 ,以及上面的欺骗 。

救援可以独自工作。 不需要始终开始和结束。

当线路上的其他内容出错时,您可以使用单线forms的rescue来返回值:

 h = { :age => 10 } h[:name].downcase # ERROR h[:name].downcase rescue "No name" 

rescue字是方法定义的一部分

但在控制器中更好地使用rescue_from来拯救错误

试试这个

 def edit begin load_elements(current_user) unless current_user.role?(:admin) respond_to do |format| format.json { render :json => @user } format.xml { render :xml => @user } format.html end rescue ActiveRecord::RecordNotFound respond_to_not_found(:json, :xml, :html) end end