Sha256: f2831c69ee2a015843da6fec947a77a75d0cdc37f0f839b64cc43d845f5d7973

Contents?: true

Size: 1.27 KB

Versions: 3

Compression:

Stored size: 1.27 KB

Contents

require 'json'
module ChatWork
  class ChatWorkError < StandardError

    def self.from_response(status, body)
      # HTTP status 204 don't have body.
      return APIError.new(status, "") if status == 204

      hash =
        begin
          JSON.load(body)
        rescue JSON::ParserError => e
          return ChatWork::APIConnectionError.new("Response JSON is broken. #{e.message}: #{body}", e)
        end
      unless hash['errors']
        return APIConnectionError.new("Invalid response #{body}")
      end

      APIError.new(status, hash['errors'])
    end

    attr_reader :status
    attr_reader :error_response

    def initialize(message, status = nil, error_response = nil)
      @status, @error_response = status, error_response
      super(message)
    end
  end

  class APIConnectionError < ChatWorkError
    def self.faraday_error(e)
      new("Connection with ChatWork API server failed. #{e.message}", e)
    end

    attr_reader :original_error

    def initialize(message, original_error)
      @original_error = original_error
      super(message)
    end
  end

  class APIError < ChatWorkError
    attr_reader :errors

    def initialize(status, error_response)
      @errors = error_response
      super(error_response[0], status, error_response)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
chatwork-0.4.1 lib/chatwork/chatwork_error.rb
chatwork-0.4.0 lib/chatwork/chatwork_error.rb
chatwork-0.3.1 lib/chatwork/chatwork_error.rb