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:
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.