Sha256: f600940644bc7babdbcb0b622c27d22d77ab35d53ad4f49c4b4bae63527419d1

Contents?: true

Size: 1.21 KB

Versions: 2

Compression:

Stored size: 1.21 KB

Contents

require 'faraday'

# @private
module Faraday
  # @private
  class Response::RaiseHttp4xx < Response::Middleware
    def self.register_on_complete(env)
      env[:response].on_complete do |response|
        case response[:status].to_i
        when 400
          raise Thounds::BadRequest, error_message(response)
        when 401
          raise Thounds::Unauthorized, error_message(response)
        when 403
          raise Thounds::Forbidden, error_message(response)
        when 404
          raise Thounds::NotFound, error_message(response)
        when 406
          raise Thounds::NotAcceptable, error_message(response)
        end
      end
    end

    def initialize(app)
      super
      @parser = nil
    end

    private

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

    def self.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

2 entries across 2 versions & 1 rubygems

Version Path
thounds-0.0.2 lib/faraday/raise_http_4xx.rb
thounds-0.0.1 lib/faraday/raise_http_4xx.rb