Sha256: 5ebbc4c70ff2e767a1c03b3d70df8018a0fa1b41528b586330807ee27c0a573f

Contents?: true

Size: 1.67 KB

Versions: 3

Compression:

Stored size: 1.67 KB

Contents

module Pin
  ##
  # Base Pin Eror class
  class PinError < Exception
    def initialize(message = nil, http_status = nil)
      @message = message
      @http_status = http_status
    end

    def to_s
      status_string = @http_status.nil? ? '' : "(Status #{@http_status}) "
      "#{status_string}#{@message}"
    end

    def self.handle_error(http_status, response)
      case http_status
      when 400
        fail(Pin::ChargeError, "#{response['error']}: #{response['error_description']}. Charge token: #{response['charge_token']}")
      when 402
        fail(Pin::InsufficientPinBalance, "#{response['error_description']}")
      when 404
        fail(Pin::ResourceNotFound, "#{response['error_description']}")
      when 422
        message = handle_bad_response(response)
        fail(Pin::InvalidResource, message)
      end
    end

    def self.handle_bad_response(response)
      message = ''
      begin
        response['messages'].each do |m|
          message += "#{m['code']}: #{m['message']} "
        end
      rescue
        begin response['messages']['amount'][0]
          message = "#{response['error']}: #{response['error_description']}. Amount: #{response['messages']['amount'][0]} "
        rescue
          message = "#{response['error']}: #{response['error_description']}"
        end
      end
      message
    end

    def self.handle_bad_request
      fail(Pin::ClientError, 'request :method must be one of get, post, put, patch or delete')
    end
  end

  class ResourceNotFound < PinError
  end

  class InvalidResource < PinError
  end

  class ChargeError < PinError
  end

  class InsufficientPinBalance < PinError
  end

  class ClientError < PinError
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
pin_up-1.0.0 lib/pin_up/pin_errors.rb
pin_up-0.10.1 lib/pin_up/pin_errors.rb
pin_up-0.10.0 lib/pin_up/pin_errors.rb