Sha256: d3ed1bfdbf3f66da529ef14c2b274c0be5f0dc1e4528539c283275485df02b74

Contents?: true

Size: 1.04 KB

Versions: 3

Compression:

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

3 entries across 3 versions & 1 rubygems

Version Path
disqussion-0.0.3 lib/faraday/response/raise_http_4xx.rb
disqussion-0.0.2 lib/faraday/response/raise_http_4xx.rb
disqussion-0.0.1 lib/faraday/response/raise_http_4xx.rb