Failsafe mixin

Maybe it’s not the most popular need, but sometimes you need to provide main feature in the most bullet proof way, so every other aspect around given feature can fail but the feature - not.

What are the requirements? It has to catch all possible exceptions on production environment, but still pass them to error notification software. It has to raise errors on staging / dev / test environments.

The implemenation is fairly easy:

1
2
3
4
5
6
7
8
9
10
11
module Failsafe
  def failsafe(&block)
    block.call
  rescue => e
    if Rails.env.production?
      ErrorNotification.error(e)
    else
      raise
    end
  end
end

You can use it this way:

1
2
3
4
5
6
7
8
9
10
class SuperImportantFeature
  include Failsafe

  def call
    important_logic!

    failsafe { less_important_logic }
    failsafe { even_less_important_logic }
  end
end

It’s super easy, but may improve user experience when things go south.