Sha256: 8435281e0e387b89a0dca9019035807893625730e5718e1d9bfdabe59458322c

Contents?: true

Size: 1.45 KB

Versions: 5

Compression:

Stored size: 1.45 KB

Contents

module ActionKitRest
  module Response
    class RaiseError < Faraday::Response::Middleware

      def on_complete(response)
        status_code = response[:status].to_i
        if (400...600).include? status_code
          if status_code == 400
            raise ActionKitRest::Response::ValidationError.new(url: response[:url].to_s, body: response[:body])
          elsif status_code == 404
            raise ActionKitRest::Response::NotFound.new(response[:url].to_s)
          elsif status_code == 401
            raise ActionKitRest::Response::Unauthorized.new(response[:url].to_s)
          elsif status_code == 500 && response[:body] =~ /\"error\"/
            error_hsh = JSON.parse(response[:body])
            error_message = error_hsh['error']

            if error_message == 'Sorry, this request could not be processed. Please try again later.'
              raise ActionKitRest::Response::TryAgainLater.new(error_message(response))
            else
              raise StandardError.new(error_message(response))
            end
          else
            raise StandardError.new(error_message(response))
          end
        end
      end

      def error_message(response)
        "#{response[:method].to_s.upcase} #{response[:url].to_s}: #{response[:status]} \n\n #{response[:body] if response[:body]}"
      end
    end

    class TryAgainLater < StandardError ; end
    class NotFound < StandardError ; end
    class Unauthorized < StandardError ; end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
action_kit_rest-0.3.4 lib/action_kit_rest/response/raise_error.rb
action_kit_rest-0.3.3 lib/action_kit_rest/response/raise_error.rb
action_kit_rest-0.3.2 lib/action_kit_rest/response/raise_error.rb
action_kit_rest-0.3.1 lib/action_kit_rest/response/raise_error.rb
action_kit_rest-0.3.0 lib/action_kit_rest/response/raise_error.rb