Sha256: e4a266d7ff916def0a6aa1c32406a0bba6072761e6055de8b291f2f475915670

Contents?: true

Size: 1.31 KB

Versions: 5

Compression:

Stored size: 1.31 KB

Contents

require 'faraday'
require 'capgun/error/bad_request'
require 'capgun/error/forbidden'
require 'capgun/error/not_acceptable'
require 'capgun/error/not_found'
require 'capgun/error/unauthorized'

module Capgun
  module Response
    class RaiseClientError < Faraday::Response::Middleware

      def on_complete(env)
        case env[:status].to_i
        when 400
          raise Capgun::Error::BadRequest.new(error_body(env[:body]), env[:response_headers])
        when 401
          raise Capgun::Error::Unauthorized.new(error_body(env[:body]), env[:response_headers])
        when 403
          raise Capgun::Error::Forbidden.new(error_body(env[:body]), env[:response_headers])
        when 404
          raise Capgun::Error::NotFound.new(error_body(env[:body]), env[:response_headers])
        when 406
          raise Capgun::Error::NotAcceptable.new(error_body(env[:body]), env[:response_headers])
        end
      end

    private

      def error_body(body)
        if body.nil?
          ''
        elsif body['message']
          body['message']
        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
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
capgun-0.2.0 lib/capgun/response/raise_client_error.rb
capgun-0.1.2 lib/capgun/response/raise_client_error.rb
capgun-0.1.1 lib/capgun/response/raise_client_error.rb
capgun-0.1.0 lib/capgun/response/raise_client_error.rb
capgun-0.0.3 lib/capgun/response/raise_client_error.rb