ActiveSupport::Rescuable 3

Posted by pratik
on Monday, November 03

In Rails 2.2, controller’s rescue_from has been extracted to ActiveSupport as ActiveSupport::Rescuable module. Relevant commits are 964dfc and 259a7a. This allows you to use rescue_from functionality in class as a cleaner way of handling exceptions.

Now you can just include ActiveSupport::Rescuable in your class and start using rescue_with_handler(exception) from your rescue blocks :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Armageddon < StandardError
end

class Earth
  include ActiveSupport::Rescuable

  rescue_from Armageddon, :with => :nuke_the_rock

  def life
    raise Armageddon
  rescue Exception => e
    rescue_with_handler(e)
  end

  def nuke_the_rock
    puts "snafu"
  end
end

e = Earth.new
e.life

The above code will produce output “snafu”. You can also check code/docs if you wanna know more.

Comments

Leave a response

  1. JustinNovember 03, 2008 @ 02:16 PM

    Why is this better than just putting “nuke_the_rock” in place of “rescue_with_handler(e)”?

  2. PratikNovember 03, 2008 @ 03:00 PM

    Because you can have 20 rescue handlers that you need to use at 50 different places :)

  3. JustinNovember 05, 2008 @ 03:30 PM

    Ah! Duh. I see it now. This is A Good Thing :)

Comment