Feature: Raising an exception in case of a non-successful response

12 views
Skip to first unread message

Marc Köhlbrugge

unread,
Apr 12, 2020, 5:00:04 PM4/12/20
to http.rb: a fast, easy-to-use Ruby HTTP client with a chainable API
Unlike many other gems, HTTP doesn't raise an exception when the response is unsuccessful due to a client side or server side error such as 404 (Not Found), or 500 (Server Error).

I needed this functionality in some situations, so I made the following feature:

module HTTP
 
class BadRequestError < Error; end
 
class UnauthorizedError < Error; end
 
class ForbiddenError < Error; end
 
class ResourceNotFoundError < Error; end
 
class ClientError < Error; end
 
class ServerError < Error; end


 
module Features
   
class Exceptions < Feature
     
def wrap_response(response)
       
case response.status.code
       
when 401
         
raise UnauthorizedError, response.status
       
when 403
         
raise ForbiddenError, response.status
       
when 404
         
raise ResourceNotFound, response.status
       
when 400..499
         
raise ClientError, response.status
       
when 500..599
         
raise ServerError, response.status
       
end


        response
     
end


      HTTP
::Options.register_feature(:exceptions, self)
   
end
 
end
end

It can be used as such:

begin
  HTTP
.use(:exceptions).get("https://google.com/does-not-exist")
rescue HTTP::ResourceNotFound
 
# 404
rescue HTTP::Error
 
# Something else
end


If the maintainers of the gem are interested, I'd be happy to create PR adding this to the gem. Alternatively, I can create a separate `http-features-exceptions` gem if there's enough interest in the community for such a thing.

Credit for the case statement goes to my colleague Jankees van Woezik.
Reply all
Reply to author
Forward
0 new messages