Exception: Johac::Error::ResponseError

Inherits:
Johac::Error
  • Object
show all
Defined in:
lib/johac/error.rb

Overview

Exception to be used when dealing with HTTP responses from a Johac API.

Direct Known Subclasses

ClientError, RetryableError, ServerError

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(status, body, headers) ⇒ ResponseError

Will attempt to decode a response body via JSON, and look for the ‘message’ key in the resulting (assumed) hash. If response body cannot be parsed via JSON the entire response body is set as the message for the exception.

Parameters:

  • body (String)

    Response body.

  • headers (Hash)

    Response headers.



19
20
21
22
23
24
25
26
27
28
# File 'lib/johac/error.rb', line 19

def initialize(status, body, headers)
  @status = status
  @headers = headers
  @body = if headers['Content-Type'] == 'application/json'
    JSON.parse(body) rescue body
  else
    body
  end
  super(body)
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



12
13
14
# File 'lib/johac/error.rb', line 12

def body
  @body
end

#headersObject (readonly)

Returns the value of attribute headers.



13
14
15
# File 'lib/johac/error.rb', line 13

def headers
  @headers
end

#statusObject (readonly)

Returns the value of attribute status.



11
12
13
# File 'lib/johac/error.rb', line 11

def status
  @status
end

Class Method Details

.from_response(status_code, headers, body) ⇒ Johac::Error::RetryableError, ...

If a problem is detected in an HTTP response, build the proper exception, otherwise return nil.

Parameters:

  • status_code (Integer)

    HTTP response code.

  • body (String)

    Response body.

  • headers (Hash)

    Response headers.

Returns:



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/johac/error.rb', line 40

def self.from_response(status_code, headers, body)
  if klass =  case status_code
              when 429 then RetryableError
              when 503 then RetryableError
              when 504 then RetryableError
              when 400..499 then ClientError
              when 500..599 then ServerError
              end
    klass.new(status_code, body, headers)
  end
end