Reputation: 45
I'm writing a script which collects data from various url's. I want to collect errors from begin rescue
blocks into an array to output them when the program runs in verbose mode. With normal use, a failed connection is ignored and the script moves on to the next url.
I thought the best way to do this would be to create an array errArray = Array.new
at the top of the script to hold errors, and then do:
rescue Exception => e
errArray << e.message
in various functions to log errors. The die
function outputs the array using p
unless it is empty. However, I get the error
Undefined local variable or method 'errArray'
Any help (and constructive criticism) appreciated.
EDIT: die function:
def die(e)
p errorArray unless errorArray.empty?
# Some other irrelevant code
end
Upvotes: 2
Views: 600
Reputation: 44725
errArray
is not global variable and therefore methods have no access to it. You can declare it as a global variable by $err_array
.
However the best solution would be create a simple class:
class ExceptionCollector
def collect
yield
rescue => e
errors << e.message
end
def errors
@errors ||= []
end
end
And then simple:
$logger = ExceptionCollector.new
$logger.collect do
# this may raise an exception
end
def foo
$logger.collect do
# another exception
end
end
$logger.errors #=> list of errors
Upvotes: 4