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 error codes and messages so include this if possible in the exception messages

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



9
10
11
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
# File 'lib/ably/rest/middleware/exceptions.rb', line 9

def call(env)
  @app.call(env).on_complete do
    if env[:status] >= 400
      error_status_code = env[:status]
      error_code = nil

      begin
        error = JSON.parse(env[:body])['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
      rescue JSON::ParserError
        message = env[:body]
      end

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

      if env[:status] >= 500
        raise Ably::Exceptions::ServerError, message
      else
        raise Ably::Exceptions::InvalidRequest.new(message, status: error_status_code, code: error_code)
      end
    end
  end
end