Sha256: c9a7c56fe2f1344f2ca521f03bdc8ff1b3e1a1175a994d8801b3bdf6a693ec8f

Contents?: true

Size: 1.29 KB

Versions: 3

Compression:

Stored size: 1.29 KB

Contents

module SphereEngine
  # Custom error class for rescuing from all SphereEngine errors
  class Error < StandardError
    # @return [Integer]
    attr_reader :code

    # Initializes a new Error object
    #
    # @param message [Exception, String]
    # @param code [Integer]
    # @return [SphereEngine::Error]
    def initialize(message = '', code = nil)
      super(message)
      @code = code
    end

    # ClientErrors(Raised when SphereEngine returns a 4xx HTTP status code)
    #
    # Raised when SphereEngine returns the HTTP status code 400
    BadRequest = Class.new(self)

    # Raised when SphereEngine returns the HTTP status code 401
    Unauthorized  = Class.new(self)

    ERRORS = {
      400 => SphereEngine::Error::BadRequest,
      401 => SphereEngine::Error::Unauthorized
    }

    class << self
      # Create a new error from an HTTP response
      #
      # @param body [String]
      # @param headers [Hash]
      # @return [SphereEngine::Error]
      def from_response(body)
        message, code = parse_error(body)
        new(message, code)
      end

    private

      def parse_error(body)
        if body.nil? || body.empty?
          ['', nil]
        elsif  body["message"] || body[:message]
          [ body["message"] || body[:message], nil]
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
sphere_engine-1.1.0 lib/sphere_engine/error.rb
sphere_engine-1.0.0 lib/sphere_engine/error.rb
sphere_engine-1.3.0.pre lib/sphere_engine/error.rb