Sha256: a8d906a62323946ac8f739fa55b0b0bca3c6d6fbb7603200640b02421e040830

Contents?: true

Size: 1.23 KB

Versions: 4

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 Evrythng::BadRequest.new(error_message(env), env[:response_headers])
      when 401
        raise Evrythng::Unauthorized.new(error_message(env), env[:response_headers])
      when 403
        raise Evrythng::Forbidden.new(error_message(env), env[:response_headers])
      when 404
        raise Evrythng::NotFound.new(error_message(env), env[:response_headers])
      when 406
        raise Evrythng::NotAcceptable.new(error_message(env), env[:response_headers])
      when 420
        raise Evrythng::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 = 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
evrythng-0.0.5 lib/faraday/response/raise_http_4xx.rb
evrythng-0.0.3 lib/faraday/response/raise_http_4xx.rb
evrythng-0.0.2 lib/faraday/response/raise_http_4xx.rb
evrythng-0.0.1 lib/faraday/response/raise_http_4xx.rb