Sha256: 8ceeb0b5c62975a0aef5c633352e05c4684471e24176289de7c65a1f9dc935c6

Contents?: true

Size: 1.39 KB

Versions: 9

Compression:

Stored size: 1.39 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 409
        raise Desk::Conflict.new(error_message(env), env[:response_headers])
      when 422
        raise Desk::Unprocessable.new(error_message(env), env[:response_headers])
      when 429
        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

9 entries across 9 versions & 1 rubygems

Version Path
desk-1.2.0 lib/faraday/response/raise_http_4xx.rb
desk-1.1.1 lib/faraday/response/raise_http_4xx.rb
desk-1.1.0 lib/faraday/response/raise_http_4xx.rb
desk-1.0.10 lib/faraday/response/raise_http_4xx.rb
desk-1.0.9 lib/faraday/response/raise_http_4xx.rb
desk-1.0.8 lib/faraday/response/raise_http_4xx.rb
desk-1.0.7 lib/faraday/response/raise_http_4xx.rb
desk-1.0.6 lib/faraday/response/raise_http_4xx.rb
desk-1.0.5 lib/faraday/response/raise_http_4xx.rb