Skip to content
This repository has been archived by the owner on Sep 5, 2019. It is now read-only.

Commit

Permalink
Merge pull request #40 from boblail/define-two-new-exception-classes
Browse files Browse the repository at this point in the history
Define exception classes for 503 and 504 responses
  • Loading branch information
JasonStoltz authored Aug 14, 2019
2 parents 134bc26 + 91b0817 commit 370d1f9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
6 changes: 6 additions & 0 deletions lib/swiftype/exceptions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
28 changes: 18 additions & 10 deletions lib/swiftype/request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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 != ''
Expand Down

0 comments on commit 370d1f9

Please sign in to comment.