How To Handle Errors In Ruby With Begin, Rescue & Ensure (RubyShorts)

How To Handle Errors In Ruby With Begin, Rescue & Ensure (RubyShorts) - Webdesign Antwerpen

Video

Catching Errors

Ruby has some built in ways which allow you to catch errors and keep your code running when it normally would have crashed. Here's what it generally looks like;

def crappy_method
  begin
    # Code that is likely to break
  rescue Exception => e # Creates a new instance of Exception and saves it as variable e
    # What to do when the code breaks
    e.message # Returns a string of the error
    e.backtrace # Returns the stack trace of the error
    # You can even add some code that will alter the result of the begin block and then call
    retry
  else
    # This runs only when no exception was raised
  ensure
    # This runs whatever happens
  end
end

Basically, put the code you think is likely to break between the begin and rescue block and whenever the code breaks, the part below the rescue block will get called, which allows you to "save" whatever you're working on.

When you include the ensure block, it will run that part whatever happens. Note: Although ensure is the last block that ran in the code, it is not the return value!

Here's an example of where I've used this in production code;

def find_xml_gz_sitemap # Checks for /sitemap.xml.gz
      puts 'No sitemap found on /sitemap or /sitemap.xml, trying sitemap.xml.gz'; write('Searching sitemap.xml.gz', 'message', 1)
      begin
        link = Timeout.timeout(10) { open("#{@site}sitemap.xml.gz", allow_redirections: :all, read_timeout: 10) }
        gz = Zlib::GzipReader.new(link)
        xml = gz.read
        @links = Nokogiri::XML.parse(xml).search('*//loc').map(&:inner_html)
        puts 'Sitemap.gz found!'; write('Sitemap found!', 'message', 1)
        has_nested_sitemap?
      rescue
        write('No sitemap :(', 'message', 1); find_robots_txt_sitemap
      end
    end

It's basically a method that checks if a certain website has a sitemap.xml.gz file and "saves" the code whenever an error occured! Pretty neat when you're not sure what your code will return.

Catch you next time! (See what I did there ;))

Resources

Want to stay updated?

Follow my RSS feed and get notified about new articles

Subscribe via RSS

Comments