ruby-on-railsrubyerror-handlingcustom-errorsairbrake

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
                    house.visitors.count
                rescue => e
                    Airbrake.notify(e)
                    0
                end

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


Solution

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

    def num_house_visitors(id)
      House.find(id).visitors.count
    rescue => e
      Airbrake.notify(e)
      0
    end
    

    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 = Struct.new('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