Sha256: 397efef8b8fc38fccbbeac1b0031c05f0dfbe752893cb909bea83ba683b61c05

Contents?: true

Size: 1.69 KB

Versions: 3

Compression:

Stored size: 1.69 KB

Contents

require 'faraday'
require 'angellist_api/error/bad_request'
require 'angellist_api/error/too_many_requests'
require 'angellist_api/error/forbidden'
require 'angellist_api/error/not_acceptable'
require 'angellist_api/error/not_found'
require 'angellist_api/error/unauthorized'

module AngellistApi
  module Response
    class RaiseClientError < Faraday::Response::Middleware
      def on_complete(env)
        case env[:status].to_i
        when 400
          raise AngellistApi::Error::BadRequest.new(error_message(env), env[:response_headers])
        when 401
          raise AngellistApi::Error::Unauthorized.new(error_message(env), env[:response_headers])
        when 403
          if env[:body]['error'] == 'over_limit'
            raise AngellistApi::Error::TooManyRequests.new(error_message(env), env[:response_headers])
          else
            raise AngellistApi::Error::Forbidden.new(error_message(env), env[:response_headers])
          end
        when 404
          raise AngellistApi::Error::NotFound.new(error_message(env), env[:response_headers])
        when 406
          raise AngellistApi::Error::NotAcceptable.new(error_message(env), env[:response_headers])
        end
      end

      private

      def error_message(env)
        "#{env[:method].to_s.upcase} #{env[:url].to_s}: #{env[:status]}#{error_body(env[:body])}"
      end

      def error_body(body)
        if body.nil?
          nil
        elsif body['error']
          ": #{body['error']}"
        elsif body['errors']
          first = Array(body['errors']).first
          if first.kind_of? Hash
            ": #{first['message'].chomp}"
          else
            ": #{first.chomp}"
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
angellist_api-1.1.0 lib/angellist_api/response/raise_client_error.rb
angellist_api-1.0.7 lib/angellist_api/response/raise_client_error.rb
angellist_api-1.0.6 lib/angellist_api/response/raise_client_error.rb