Sha256: e480ca436a909c63a395ba418603d15883f7fc4d9ea5b9110bc93291ecd1b163

Contents?: true

Size: 991 Bytes

Versions: 10

Compression:

Stored size: 991 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']


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

        if  !content_type.nil? && content_type.include?('json')
          raise errors_collection(env, error_klass)
        else
          error = {:error=>{:code=>status, :message=>"Unknown error occurred."}, :meta=>{}}
          raise error_klass.new(error)
        end
      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

10 entries across 10 versions & 1 rubygems

Version Path
basecrm-2.0.0 lib/basecrm/middlewares/raise_error.rb
basecrm-1.3.10 lib/basecrm/middlewares/raise_error.rb
basecrm-1.3.9 lib/basecrm/middlewares/raise_error.rb
basecrm-1.3.8 lib/basecrm/middlewares/raise_error.rb
basecrm-1.3.7 lib/basecrm/middlewares/raise_error.rb
basecrm-1.3.6 lib/basecrm/middlewares/raise_error.rb
basecrm-1.3.5 lib/basecrm/middlewares/raise_error.rb
basecrm-1.3.4 lib/basecrm/middlewares/raise_error.rb
basecrm-1.3.3 lib/basecrm/middlewares/raise_error.rb
basecrm-1.3.2 lib/basecrm/middlewares/raise_error.rb