Ipsum Ipsum - 1 year ago 76
Ruby Question

Collecting exceptions in ruby script

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
function outputs the array using
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

Answer Source

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
  rescue => e
    errors << e.message

  def errors
    @errors ||= []

And then simple:

$logger = ExceptionCollector.new

$logger.collect do
  # this may raise an exception

def foo
  $logger.collect do
    # another exception

$logger.errors    #=> list of errors 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download