--00235447198087493604b65ec599
Content-Type: text/plain; charset=UTF-8

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?
>
>
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
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  il.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

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

--00235447198087493604b65ec599--