Class: Ably::Rest::Middleware::Exceptions

Inherits:
Faraday::Response::Middleware
  • Object
show all
Defined in:
lib/ably/rest/middleware/exceptions.rb

Overview

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

Constant Summary collapse

TOKEN_EXPIRED_CODE =
40140..40149

Instance Method Summary collapse

Instance Method Details

#on_complete(env) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/ably/rest/middleware/exceptions.rb', line 12

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 && TOKEN_EXPIRED_CODE.include?(error_code)
      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