sclem72 sclem72 - 1 year ago 84
Ruby Question

Error handling when Exception / Error is thrown

I'll try to keep it short a sweet.

In ruby, what would be the best way to return another value if an exception is thrown? I have airbrake to notify me of the exception for me, but I do not want to stop the process from continuing. So far I have something like this:

house = House.find(1)
visitor_count = begin
rescue => e

Wondering if there is anyway to do this other than a begin block. Thanks!

Answer Source

Your solution (in isolation) is fine. Here's another way of organizing the same logic:

def num_house_visitors(id)
rescue => e

I would recommend that you try to handle or prevent exception cases from happening in the first place, though:

house = House.find_by(id: id) # assuming Rails/ActiveRecord
house ='MissingHouse', :visitors).new([]) if house.nil? # prevent nil errors

# House#visitors (and MissingHouse#visitors) always returns an array
vistor_count = house.visitors.count # this can't fail
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download