[ACCEPTED]-Why can't we access local variable inside rescue?-ruby

Accepted answer
Score: 38

You most certainly can access local variables 11 defined in a begin, in the corresponding rescue block 10 (assuming of course, the exception has been 9 raised, after the variable was set).

What 8 you can't do is access local variables that 7 are defined inside a block, outside of the 6 block. This has nothing to do with exceptions. See 5 this simple example:

define transaction() yield end
transaction do
  x = 42
end
puts x # This will cause an error because `x` is not defined here.

What you can do to fix 4 this, is to define the variable before the 3 block (you can just set it to nil) and then 2 set it inside the block.

x = nil
transaction do
  x = 42
end
puts x # Will print 42

So if you change 1 your code like this, it will work:

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
Score: 0

You can pick up error message from ActiveRecord::RecordInvalid. It 2 can be seen on official document example 1 here.

https://api.rubyonrails.org/v6.1.3.2/classes/ActiveRecord/RecordInvalid.html

begin
  transaction
    Class.create! attributes
  end 
rescue ActiveRecord::RecordInvalid => invalid
  puts invalid.record.error.full_messages
end

More Related questions