Sha256: 90a2b848cffdc34c5e4c728c5c42c34b83fc78322c870cfc5dede7f5d198e4ae

Contents?: true

Size: 1.23 KB

Versions: 13

Compression:

Stored size: 1.23 KB

Contents

require 'faraday'

# @private
module Faraday
  # @private
  class Response::RaiseHttp4xx < Response::Middleware
    def on_complete(env)
      case env[:status].to_i
      when 400
        raise Assistly::BadRequest.new(error_message(env), env[:response_headers])
      when 401
        raise Assistly::Unauthorized.new(error_message(env), env[:response_headers])
      when 403
        raise Assistly::Forbidden.new(error_message(env), env[:response_headers])
      when 404
        raise Assistly::NotFound.new(error_message(env), env[:response_headers])
      when 406
        raise Assistly::NotAcceptable.new(error_message(env), env[:response_headers])
      when 420
        raise Assistly::EnhanceYourCalm.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 = body['errors'].to_a.first
        if first.kind_of? Hash
          ": #{first['message'].chomp}"
        else
          ": #{first.chomp}"
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
assistly-0.2.6 lib/faraday/response/raise_http_4xx.rb
assistly-0.2.5 lib/faraday/response/raise_http_4xx.rb
assistly-0.2.4 lib/faraday/response/raise_http_4xx.rb
assistly-0.2.3 lib/faraday/response/raise_http_4xx.rb
assistly-0.2.2 lib/faraday/response/raise_http_4xx.rb
assistly-0.2.1 lib/faraday/response/raise_http_4xx.rb
assistly-0.2.0 lib/faraday/response/raise_http_4xx.rb
assistly-0.1.5 lib/faraday/response/raise_http_4xx.rb
assistly-0.1.4 lib/faraday/response/raise_http_4xx.rb
assistly-0.1.3 lib/faraday/response/raise_http_4xx.rb
assistly-0.1.2 lib/faraday/response/raise_http_4xx.rb
assistly-0.1.1 lib/faraday/response/raise_http_4xx.rb
assistly-0.1 lib/faraday/response/raise_http_4xx.rb