Sha256: 3de0fdacf125159a9ef1a6342345e3fbe6d28fec9789af7500f71a97bd7c957f

Contents?: true

Size: 1.45 KB

Versions: 8

Compression:

Stored size: 1.45 KB

Contents

require 'faraday'
require 'json'

module Ably
  module Rest
    module Middleware
      # HTTP exceptions raised by Ably due to an error status code
      # Ably returns JSON/Msgpack error codes and messages so include this if possible in the exception messages
      class Exceptions < Faraday::Response::Middleware
        def on_complete(env)
          if env.status >= 400
            error_status_code = env.status
            error_code = nil

            if env.body.kind_of?(Hash)
              error = env.body.fetch('error', {})
              error_status_code = error['statusCode'].to_i if error['statusCode']
              error_code = error['code'].to_i if error['code']

              if error
                message = "#{error['message']} (status: #{error_status_code}, code: #{error_code})"
              else
                message = env.body
              end
            else
              message = env.body
            end

            message = 'Unknown server error' if message.to_s.strip == ''

            if env.status >= 500
              raise Ably::Exceptions::ServerError.new(message, error_status_code, error_code)
            elsif env.status == 401 && error_code == 40140
              raise Ably::Exceptions::TokenExpired.new(message, error_status_code, error_code)
            else
              raise Ably::Exceptions::InvalidRequest.new(message, error_status_code, error_code)
            end
          end
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 2 rubygems

Version Path
ably-0.8.7 lib/ably/rest/middleware/exceptions.rb
ably-0.8.6 lib/ably/rest/middleware/exceptions.rb
ably-rest-0.8.6 lib/submodules/ably-ruby/lib/ably/rest/middleware/exceptions.rb
ably-rest-0.8.5 lib/submodules/ably-ruby/lib/ably/rest/middleware/exceptions.rb
ably-0.8.5 lib/ably/rest/middleware/exceptions.rb
ably-0.8.4 lib/ably/rest/middleware/exceptions.rb
ably-rest-0.8.3 lib/submodules/ably-ruby/lib/ably/rest/middleware/exceptions.rb
ably-0.8.3 lib/ably/rest/middleware/exceptions.rb