1

I would like to create a block of code that is not allowed to raise an exception. Is this possible?

My use case is that I have a block of code that fetches content from a 3rd party service and merges it into my main index. I don't want my application to be dependent on this 3rd party service in the event that it is down, or changes response format, etc., so how can I make a block of code that simply is not allowed to raise an error? I know I could do the following, but it seems unclean and my editor gives me

def index
  @events = current_user.events

  begin
    other_events = get_content_from_3rd_party_api
    @events.concat(other_events)
    @events.sort! { |a, b| b.created_at <=> a.created_at }
  rescue
  end

end

or

def index
  @events = current_user.events
  other_events = get_content_from_3rd_party_api
  @events.concat(other_events)
  @events.sort! { |a, b| b.created_at <=> a.created_at }
  rescue
end

but those both seem unclean

OneChillDude
  • 7,856
  • 10
  • 40
  • 79
  • 1
    That's probably how you would do it if that's *really* your goal. See this [link](http://stackoverflow.com/questions/10048173/why-is-it-bad-style-to-rescue-exception-e-in-ruby) for why this is a bad idea though. If something happens to the service, you *should* be catching that error and handling it gracefully. – mralexlau Mar 21 '14 at 22:23
  • @mralexlau `rescue` is not the same as `rescue Exception`, thank you for your reply though. `rescue` without an argument rescues `StandardError` – OneChillDude Mar 21 '14 at 22:28

1 Answers1

3

Cleaner to make it explicit with a method that names the pattern:

def swallow_error
  yield
rescue
end

def index
  @events = current_user.events

  swallow_error do
    other_events = get_content_from_3rd_party_api
    @events.concat(other_events)
    @events.sort! { |a, b| b.created_at <=> a.created_at }
  end
end
Mori
  • 27,279
  • 10
  • 68
  • 73