lib/paysafe/error.rb in paysafe-0.9.4 vs lib/paysafe/error.rb in paysafe-0.10.0
- old
+ new
@@ -46,11 +46,11 @@
ServiceUnavailable = Class.new(ServerError)
# Raised on the HTTP status code 504
GatewayTimeout = Class.new(ServerError)
- ERRORS = {
+ ERRORS_BY_STATUS = {
400 => Paysafe::Error::BadRequest,
401 => Paysafe::Error::Unauthorized,
402 => Paysafe::Error::RequestDeclined,
403 => Paysafe::Error::Forbidden,
404 => Paysafe::Error::NotFound,
@@ -63,28 +63,18 @@
502 => Paysafe::Error::BadGateway,
503 => Paysafe::Error::ServiceUnavailable,
504 => Paysafe::Error::GatewayTimeout,
}
- # The Paysafe API Error Code
- #
- # @return [Integer]
- attr_reader :code
-
- # The JSON HTTP response in Hash form
- #
- # @return [Hash]
- attr_reader :response
-
class << self
# Create a new error from an HTTP response
#
# @param body [String]
- # @param code [Integer]
+ # @param status [Integer]
# @return [Paysafe::Error]
- def from_response(body, code)
- klass = ERRORS[code] || Paysafe::Error
+ def from_response(body, status)
+ klass = ERRORS_BY_STATUS[status] || Paysafe::Error
message, error_code = parse_error(body)
klass.new(message: message, code: error_code, response: body)
end
private
@@ -96,18 +86,66 @@
[ '', nil ]
end
end
end
+ # The Paysafe API Error Code
+ #
+ # @return [String]
+ attr_reader :code
+
+ # The JSON HTTP response in Hash form
+ #
+ # @return [Hash]
+ attr_reader :response
+
# Initializes a new Error object
#
# @param message [Exception, String]
- # @param code [Integer]
+ # @param code [String]
# @param response [Hash]
# @return [Paysafe::Error]
def initialize(message: '', code: nil, response: {})
- super(message)
@code = code
@response = response
+ super(message)
end
+
+ def to_s
+ [ super, code_text, field_error_text, detail_text ].compact.join(' ')
+ end
+
+ def id
+ response.dig(:id) if response.is_a?(Hash)
+ end
+
+ def merchant_ref_num
+ response.dig(:merchant_ref_num) if response.is_a?(Hash)
+ end
+
+ private
+
+ def code_text
+ "(Code #{code})" if code
+ end
+
+ def field_error_text
+ if field_errors
+ msgs = field_errors.map { |f| "The \`#{f[:field]}\` #{f[:error]}." }.join(' ')
+ "Field Errors: #{msgs}".strip
+ end
+ end
+
+ def field_errors
+ response.dig(:error, :field_errors) if response.is_a?(Hash)
+ end
+
+ def detail_text
+ "Details: #{details.join('. ')}".strip if details
+ end
+
+ def details
+ response.dig(:error, :details) if response.is_a?(Hash)
+ end
+
end
end