Sha256: 8436fbf2c20adcc34e211b373ea315375208864639e2f1e5439c71b040a7c8ad

Contents?: true

Size: 1.16 KB

Versions: 4

Compression:

Stored size: 1.16 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 Rainmaker::BadRequest.new(error_message(env), env[:response_headers])
      when 401
        raise Rainmaker::Unauthorized.new(error_message(env), env[:response_headers])
      when 403
        raise Rainmaker::Forbidden.new(error_message(env), env[:response_headers])
      when 404
        raise Rainmaker::NotFound.new(error_message(env), env[:response_headers])
      when 422
        raise Rainmaker::Invalid.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

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rainmaker-0.1.4 lib/faraday/response/raise_http_4xx.rb
rainmaker-0.1.3 lib/faraday/response/raise_http_4xx.rb
rainmaker-0.1.1 lib/faraday/response/raise_http_4xx.rb
rainmaker-0.0.1 lib/faraday/response/raise_http_4xx.rb