Sha256: 7a56d21036d4bf44c3ecaaafd66c78b3122e6b8d7c993f75d6f5467cc4828c07

Contents?: true

Size: 891 Bytes

Versions: 11

Compression:

Stored size: 891 Bytes

Contents

module BaseCRM
  module Middlewares
    class RaiseError < Faraday::Response::Middleware

      def on_complete(env)
        status = env[:status]
        return if (200...300).member?(status)

        content_type = env[:response_headers]['content-type']

        unless content_type.include?('json')
          raise "status=#{status} error=Unknown error occurred."
        end

        error_klass = case status
        when 422 then BaseCRM::ResourceError
        when 400...500 then BaseCRM::RequestError
        when 500...600 then BaseCRM::ServerError
        end

        raise errors_collection(env, error_klass)
      end

      def errors_collection(env, error_klass)
        envelope = JSON.parse(env[:body], symbolize_names: true)
        errors = envelope[:errors]
        ErrorsCollection.new(errors.map { |e| error_klass.new(e) }, envelope[:meta])
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
basecrm-1.3.1 lib/basecrm/middlewares/raise_error.rb
basecrm-1.3.0 lib/basecrm/middlewares/raise_error.rb
basecrm-1.2.3 lib/basecrm/middlewares/raise_error.rb
basecrm-1.2.2 lib/basecrm/middlewares/raise_error.rb
basecrm-1.2.1 lib/basecrm/middlewares/raise_error.rb
basecrm-1.2.0 lib/basecrm/middlewares/raise_error.rb
basecrm-1.1.3 lib/basecrm/middlewares/raise_error.rb
basecrm-1.1.2 lib/basecrm/middlewares/raise_error.rb
basecrm-1.1.1 lib/basecrm/middlewares/raise_error.rb
basecrm-1.1.0 lib/basecrm/middlewares/raise_error.rb
basecrm-1.0.0 lib/basecrm/middlewares/raise_error.rb