HiveBrain v1.2.0
Get Started
← Back to all entries
debugrubyModerate

Handling many networking exceptions in Ruby

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
handlingexceptionsnetworkingmanyruby

Problem

What would be a prettier/faster way to do handling of multiple errors in Ruby? Here is the code I am working with:

begin
  response = session.get url
rescue Patron::HostResolutionError
  puts "Error resolving remote host."
  exit 1
rescue Patron::PartialFileError
  puts "File size mismatch. (Host reported a file size, but the actual file is of different size)"
  exit 1
rescue Patron::TimeoutError
  puts "Operation timed out."
  exit 1
rescue Patron::TooManyRedirects
  puts "Tried redirecting too many times."
  exit 1
rescue Patron::URLFormatError
  puts "Error with the URL format"
  exit 1
rescue Patron::UnsupportedProtocol
  puts "This URL is using a protocol that we cannot handle."
  exit 1
rescue Patron::ConnectionFailed
  puts "Error connecting to host. Check your internet connection."
  exit 1
end

Solution

Since you're rescuing all 7 subclasses of Patron::Error, it would make sense to directly rescue Patron::Error rather than rescuing them one by one.

You're also duplicating work that has already been done for you, by formulating your own error message for each exception: the exceptions will already contain a useful error message, which even contains more information than yours do (for example if the host could not be resolved, the exception's message will contain the hostname that could not be resolved instead of just saying "Error resolving remote host").

Lastly I would print error messages to stderr, not stdout, as that's where they're supposed to go.

So I would write the code like this:

begin
  response = session.get url
rescue Patron::Error => e
  $stderr.puts e.message
  exit 1
end

Code Snippets

begin
  response = session.get url
rescue Patron::Error => e
  $stderr.puts e.message
  exit 1
end

Context

StackExchange Code Review Q#2049, answer score: 15

Revisions (0)

No revisions yet.