局部变量
begin transaction #Code inside transaction object = Class.new attributes raise unless object.save! end rescue puts object.error.full_messages # Why can't we use local varible inside rescue ? end
实例变量
begin transaction #Code inside transaction @object = Class.new attributes raise unless @object.save! end rescue puts @object.error.full_messages # This is working fine. end
解决方法
您当然可以在相应的救援块中访问begin中定义的局部变量(当然,假设在设置变量之后引发了异常).
您不能做的是访问块外部块内定义的局部变量.这与例外无关.看这个简单的例子:
define transaction() yield end transaction do x = 42 end puts x # This will cause an error because `x` is not defined here.
你可以做些什么来解决这个问题,就是在块之前定义变量(你可以将它设置为nil),然后在块内设置它.
x = nil transaction do x = 42 end puts x # Will print 42
因此,如果您像这样更改代码,它将起作用:
begin object = nil transaction do #Code inside transaction object = Class.new attributes raise unless object.save! end rescue puts object.error.full_messages # Why can't we use local varible inside rescue ? end