Sha256: 78c7795c264c1298f1fb38ac8ca5efc742cafd06a7b089c79154e869bf977676

Contents?: true

Size: 1.21 KB

Versions: 5

Compression:

Stored size: 1.21 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 Desk::BadRequest.new(error_message(env), env[:response_headers])
      when 401
        raise Desk::Unauthorized.new(error_message(env), env[:response_headers])
      when 403
        raise Desk::Forbidden.new(error_message(env), env[:response_headers])
      when 404
        raise Desk::NotFound.new(error_message(env), env[:response_headers])
      when 406
        raise Desk::NotAcceptable.new(error_message(env), env[:response_headers])
      when 420
        raise Desk::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

5 entries across 5 versions & 1 rubygems

Version Path
desk-1.0.0 lib/faraday/response/raise_http_4xx.rb
desk-0.3.3 lib/faraday/response/raise_http_4xx.rb
desk-0.3.2 lib/faraday/response/raise_http_4xx.rb
desk-0.3.1 lib/faraday/response/raise_http_4xx.rb
desk-0.3.0 lib/faraday/response/raise_http_4xx.rb