|
|
# From http://tammersaleh.com/posts/rescuing-net-http-exceptions
require 'net/http'
#=> true
# The ancestors beforehand
Net::HTTPBadResponse.ancestors
#=> [Net::HTTPBadResponse, StandardError, Exception, Object, Wirble::Shortcuts, PP::ObjectMixin, Kernel]
# Define the module to use for catching the exceptions
module Net::HTTPBroken; end
#=> nil
# Include the module into the exceptions
[Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse,
Net::HTTPHeaderSyntaxError, Net::ProtocolError].each {|m| m.send(:include, Net::HTTPBroken)}
#=> [Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError]
# Now the exceptions have the module in their ancestry
Timeout::Error.ancestors
#=> [Timeout::Error, Net::HTTPBroken, Interrupt, SignalException, Exception, Object, Wirble::Shortcuts, PP::ObjectMixin, Kernel]
Net::HTTPBadResponse.ancestors
#=> [Net::HTTPBadResponse, Net::HTTPBroken, StandardError, Exception, Object, Wirble::Shortcuts, PP::ObjectMixin, Kernel]
# Lets check whether it works
begin; raise Net::HTTPBadResponse, "Got a bad response!"; rescue Net::HTTPBroken => e; puts e.message; end
# Got a bad response!
#=> nil
begin; raise Errno::EINVAL, "Invalid!"; rescue Net::HTTPBroken => e; puts e.message; end
# Invalid argument - Invalid!
#=> nil
# Win!
|