Sha256: 0370008f51868adfd3c3e4a5a2a8a61b57955897c4a1ddc2d792d8a1f6f565e5

Contents?: true

Size: 1.17 KB

Versions: 1

Compression:

Stored size: 1.17 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

1 entries across 1 versions & 1 rubygems

Version Path
rainmaker-0.1.5 lib/faraday/response/raise_http_4xx.rb