Error Handling

Hi folks,

I only knows very basic error handing, say
begin
  test1() # test1() will call some api call from other library,
          # if it failed, it will generate some error message
          # and exit the program
rescue
  puts "test1 failed"
end

begin
  test2() # similiar to test1() but different error message
rescue
  puts "test2 failed"
end

This is really tedious.
Is there any other way that I can have only one set of begin/rescue/end?

I am imaging some mechanism like use regex to search the error message
for key word?

thanks,

David

···

--
Posted via http://www.ruby-forum.com/.

Don't regex on the message (they might change).

Do matching on the Exception class (rescue e ; e.is_a?ZeroDivisionError)

You can rescue separate exceptions with separate rescue clauses.
And even if you would only use 1 rescue, match on the exception class.
e.to_s gives the message.
e.class gives the exception class

An example:

peterv@ASUS:~$ cat t1.rb
begin
  a = 0/0
rescue ZeroDivisionError => e
  puts "This was a division by zero : #{e.inspect}"
rescue Exception => e
  puts "This was another exception : #{e.inspect}"
end

peterv@ASUS:~$ ruby t1.rb
This was a division by zero : #<ZeroDivisionError: divided by 0>

peterv@ASUS:~$ vim t1.rb # to trigger a different Exception sub class

peterv@ASUS:~$ cat t1.rb
begin
  a = nil.foo
rescue ZeroDivisionError => e
  puts "This was a division by zero : #{e.inspect}"
rescue Exception => e
  puts "This was another exception : #{e.inspect}"
end

peterv@ASUS:~$ ruby t1.rb
This was another exception : #<NoMethodError: undefined method `foo' for
nil:NilClass>

HTH,

Peter

···

On Fri, Jan 13, 2012 at 2:09 AM, tan yeun <tayetemp@gmail.com> wrote:

Hi folks,

I only knows very basic error handing, say
begin
test1() # test1() will call some api call from other library,
         # if it failed, it will generate some error message
         # and exit the program
rescue
puts "test1 failed"
end

begin
test2() # similiar to test1() but different error message
rescue
puts "test2 failed"
end

This is really tedious.
Is there any other way that I can have only one set of begin/rescue/end?

I am imaging some mechanism like use regex to search the error message
for key word?

--
Peter Vandenabeele
http://twitter.com/peter_v
http://rails.vandenabeele.com

You can use the power of ruby blocks:

def run_test(name, &block)
  yield
rescue
  puts "#{name} failed"
end

run_test "test1" do
  # run test 1
end

run_test "test2" do
  # run test 2
end

···

--
Posted via http://www.ruby-forum.com/.