class Unleashed::Error

Custom error class for rescuing from all Unleashed errors

Public Class Methods

from_response(response, errors_format = nil) click to toggle source

Returns the appropriate Unleashed::Error subclass based on status

@param [Faraday::Response] response Faraday HTTP response @return [Unleashed::Error]

# File lib/unleashed/error.rb, line 8
def self.from_response(response, errors_format = nil)
  klass = case response.status
          when 400      then Unleashed::BadRequest
          when 401      then Unleashed::Unauthorized
          when 403      then Unleashed::Forbidden
          when 404      then Unleashed::NotFound
          when 405      then Unleashed::MethodNotAllowed
          when 406      then Unleashed::NotAcceptable
          when 409      then Unleashed::Conflict
          when 422      then Unleashed::UnprocessableEntity
          when 400..499 then Unleashed::ClientError
          when 500      then Unleashed::InternalServerError
          when 501      then Unleashed::NotImplemented
          when 502      then Unleashed::BadGateway
          when 503      then Unleashed::ServiceUnavailable
          when 500..599 then Unleashed::ServerError
          end
  klass ? klass.new(response, errors_format) : new(response, errors_format)
end
new(response = nil, errors_format = nil) click to toggle source
Calls superclass method
# File lib/unleashed/error.rb, line 28
def initialize(response = nil, errors_format = nil)
  @response = response
  @errors_format = errors_format
  super(build_error_message)
end

Private Instance Methods

build_error_message() click to toggle source
# File lib/unleashed/error.rb, line 36
def build_error_message
  return nil if @response.nil? || @response.body.nil?

  case @errors_format
  when 'raw'
    @response.body
  else
    json_response = JSON.parse(@response.body)
    message = "[StatusCode=#{@response.status}] - "
    message << json_response['description'] if json_response.key?('description')
    message << json_response['Description'] if json_response.key?('Description')

    if json_response.key?('Items') && json_response['Items'].is_a?(Array)
      message << json_response['Items'].map { |attribute, content| "#{attribute}: #{content}" }.join(', ')
    end

    message
  end
end