Sha256: 0f53da73154bd16e5030074d816830994c1267ac82cdb4a6adf05455955a1506

Contents?: true

Size: 1.44 KB

Versions: 2

Compression:

Stored size: 1.44 KB

Contents

require 'faraday'
require 'evrythng/error/bad_request'
require 'evrythng/error/enhance_your_calm'
require 'evrythng/error/forbidden'
require 'evrythng/error/not_acceptable'
require 'evrythng/error/not_found'
require 'evrythng/error/unauthorized'

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

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

      private

      def error_body(body)
        if body.nil?
          ''
        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

2 entries across 2 versions & 1 rubygems

Version Path
evrythng-0.1.1 lib/evrythng/response/raise_client_error.rb
evrythng-0.1.0 lib/evrythng/response/raise_client_error.rb