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

 - Webdesign Mechelen

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


Questions/Suggestions?

Related Articles

 - Webdesign Mechelen

How to Upload Subscribers to Mailchimp Using CSV File (RubyShorts)

Ever wanted to bulk upload users to your mailchimp account but were hindered because of the omnivore alert? Well with some magical ruby code and an API-key you won't have any problems :)

 - Webdesign Mechelen

How To Install OneNote On Ubuntu (2017)

Do you love keeping your notes in OneNote, made by Microsoft and can't really live without it? Well in this video I'm going to show you how you can set it up on your linux ubuntu device.

 - Webdesign Mechelen

How To Create An Automatic Sitemap For Your Rails App On Heroku (RailsShorts)

Wish your sitemap was automatically updated once a week or faster without having to manually update it and push the changes to your server? Combine sitemap generator & fog to fix this!

 - Webdesign Mechelen

How To Do Basic CSV Manipulations In Ruby (RubyShorts)

Need some basic stuff done on your CSV like creating, reading, writing or appending? Here's a short overview!

 - Webdesign Mechelen

How To Query A Basic API In Ruby (RubyShorts)

Here's a quick article on how you can quickly retrieve data from an API endpoint using the open-uri and json library

How to Upload Subscribers to Mailchimp Using CSV File (RubyShorts)

Ever wanted to bulk upload users to your mailchimp account but were hindered because of the omnivore alert? Well with some magical ruby code and an API-key you won't have any problems :)

How To Install OneNote On Ubuntu (2017)

Do you love keeping your notes in OneNote, made by Microsoft and can't really live without it? Well in this video I'm going to show you how you can set it up on your linux ubuntu device.

How To Create An Automatic Sitemap For Your Rails App On Heroku (RailsShorts)

Wish your sitemap was automatically updated once a week or faster without having to manually update it and push the changes to your server? Combine sitemap generator & fog to fix this!

How To Do Basic CSV Manipulations In Ruby (RubyShorts)

Need some basic stuff done on your CSV like creating, reading, writing or appending? Here's a short overview!

How To Query A Basic API In Ruby (RubyShorts)

Here's a quick article on how you can quickly retrieve data from an API endpoint using the open-uri and json library