How to check for specific rescue clause for error handling in Rails 3.x?
Asked Answered
T

3

10

I have the following code:

begin
  site = RedirectFollower.new(url).resolve
rescue => e
  puts e.to_s
  return false
end

Which throws errors like:

the scheme http does not accept registry part: www.officedepot.com;

the scheme http does not accept registry part: ww2.google.com/something;

Operation timed out - connect(2)

How can I add in another rescue for all errors that are like the scheme http does not accept registry part?

Since I want to do something other than just printing the error and returning false in that case.

Tullus answered 29/11, 2011 at 21:34 Comment(0)
H
16

That depends.

I see the three exception descriptions are different. Are the Exception types different as well?

If So you could write your code like this:

begin
  site = RedirectFollower.new(url).resolve
rescue ExceptionType1 => e
  #do something with exception that throws 'scheme http does not...'
else
  #do something with other exceptions
end

If the exception types are the same then you'll still have a single rescue block but will decide what to do based on a regular expression. Perhaps something like:

begin
  site = RedirectFollower.new(url).resolve
rescue Exception => e
  if e.message =~ /the scheme http does not accept registry part/
      #do something with it
  end
end

Does this help?

Helpful answered 29/11, 2011 at 22:4 Comment(0)
P
6

Check what is exception class in case of 'the scheme http does not accept registry part' ( you can do this by puts e.class). I assume that this will be other than 'Operation timed out - connect(2)'

then:

begin
  .
rescue YourExceptionClass => e
  .
rescue => e
  .
end
Pixilated answered 29/11, 2011 at 21:59 Comment(0)
C
1

Important Note: Rescue with wildcard, defaults to StandardError. It will not rescue every error.

For example, SignalException: SIGTERMwill not be rescued with rescue => error. You will have to specifically use rescue SignalException => e.

Cheng answered 11/10, 2017 at 17:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.