Sha256: fc3d20ca73016c3cbc54bcbb5e1bb0048bfff328a8638071aca338eb53f1021a

Contents?: true

Size: 1.57 KB

Versions: 8

Compression:

Stored size: 1.57 KB

Contents

require 'faraday'

# @private
module FaradayMiddleware
  # @private
  class RaiseHttpException < Faraday::Middleware
    def call(env)
      @app.call(env).on_complete do |response|
        case response[:status].to_i
        when 400
          raise Instagram::BadRequest, error_message_400(response)
        when 404
          raise Instagram::NotFound, error_message_400(response)
        when 500
          raise Instagram::InternalServerError, error_message_500(response, "Something is technically wrong.")
        when 503
          raise Instagram::ServiceUnavailable, error_message_500(response, "Instagram is rate limiting your requests.")
        end
      end
    end

    def initialize(app)
      super app
      @parser = nil
    end

    private

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

    def error_body(body)
      # body gets passed as a string, not sure if it is passed as something else from other spots?
      if not body.nil? and not body.empty? and body.kind_of?(String)
        # removed multi_json thanks to wesnolte's commit
        body = ::JSON.parse(body)
      end

      if body.nil?
        nil
      elsif body['meta'] and body['meta']['error_message'] and not body['meta']['error_message'].empty?
        ": #{body['meta']['error_message']}"
      end
    end

    def error_message_500(response, body=nil)
      "#{response[:method].to_s.upcase} #{response[:url].to_s}: #{[response[:status].to_s + ':', body].compact.join(' ')}"
    end
  end
end

Version data entries

8 entries across 8 versions & 2 rubygems

Version Path
instagram-0.11.0 lib/faraday/raise_http_exception.rb
instagram_geo-0.8.8 lib/faraday/raise_http_exception.rb
instagram-0.10.0 lib/faraday/raise_http_exception.rb
instagram-0.9.1 lib/faraday/raise_http_exception.rb
instagram-0.9.0 lib/faraday/raise_http_exception.rb
instagram_geo-0.8.7 lib/faraday/raise_http_exception.rb
instagram-0.8.5 lib/faraday/raise_http_exception.rb
instagram-0.8.4 lib/faraday/raise_http_exception.rb