RubyG
RubyG

Reputation: 13

How to catch different error types at the same time?

I have the following code to help me catch redirect errors when processing URLs.

begin
  page = Nokogiri::HTML(uri.open(redirect: false))
rescue OpenURI::HTTPRedirect => redirect
  uri = redirect.uri
  puts "retry #{tries}: #{uri}"
  retry if (tries-=1) > 0
  raise

It works well for URL redirect errors, but it doesn't catch any other types of errors. For example, a URL threw a 416 error, which couldn't be handled by the above code.

I can use

rescue StandardError => e

to catch the 416 error and skip the URL I was processing, but how do I catch both errors at the same time so that when there is a redirect error, the code knows where to redirect, and when there are other types of errors, the code knows when to skip?

Upvotes: 0

Views: 48

Answers (1)

siopao
siopao

Reputation: 318

Just need to put in another rescue. You can put in as many as you need.

begin
  page = Nokogiri::HTML(uri.open(redirect: false))
rescue OpenURI::HTTPRedirect => redirect
  uri = redirect.uri
  puts "retry #{tries}: #{uri}"
  retry if (tries-=1) > 0
  raise
rescue OtherError => e
  # do something

Upvotes: 4

Related Questions