diff --git a/lib/swiftype/exceptions.rb b/lib/swiftype/exceptions.rb index 611e467..8d43ebc 100644 --- a/lib/swiftype/exceptions.rb +++ b/lib/swiftype/exceptions.rb @@ -6,4 +6,10 @@ class InvalidCredentials < ClientException; end class BadRequest < ClientException; end class Forbidden < ClientException; end class UnexpectedHTTPException < ClientException; end + + class ServerException < StandardError; end + class InternalServerError < ServerException; end + class BadGateway < ServerException; end + class ServiceUnavailable < ServerException; end + class GatewayTimeout < ServerException; end end diff --git a/lib/swiftype/request.rb b/lib/swiftype/request.rb index 8dd187b..646c403 100644 --- a/lib/swiftype/request.rb +++ b/lib/swiftype/request.rb @@ -89,21 +89,29 @@ def handle_errors(response) case response when Net::HTTPSuccess response - when Net::HTTPUnauthorized - raise Swiftype::InvalidCredentials, error_message_from_response(response) - when Net::HTTPNotFound - raise Swiftype::NonExistentRecord, error_message_from_response(response) - when Net::HTTPConflict - raise Swiftype::RecordAlreadyExists, error_message_from_response(response) - when Net::HTTPBadRequest - raise Swiftype::BadRequest, error_message_from_response(response) - when Net::HTTPForbidden - raise Swiftype::Forbidden, error_message_from_response(response) else + EXCEPTION_MAP.each do |response_class, exception_class| + if response.is_a?(response_class) + raise exception_class, error_message_from_response(response) + end + end + raise Swiftype::UnexpectedHTTPException, "#{response.code} #{response.body}" end end + EXCEPTION_MAP = { + Net::HTTPUnauthorized => Swiftype::InvalidCredentials, + Net::HTTPNotFound => Swiftype::NonExistentRecord, + Net::HTTPConflict => Swiftype::RecordAlreadyExists, + Net::HTTPBadRequest => Swiftype::BadRequest, + Net::HTTPForbidden => Swiftype::Forbidden, + Net::HTTPInternalServerError => Swiftype::InternalServerError, + Net::HTTPBadGateway => Swiftype::BadGateway, + Net::HTTPServiceUnavailable => Swiftype::ServiceUnavailable, + Net::HTTPGatewayTimeOut => Swiftype::GatewayTimeout + }.freeze + def error_message_from_response(response) body = response.body json = JSON.parse(body) if body && body.strip != ''