Exception: CopyAi::HTTPError

Inherits:
Error
  • Object
show all
Defined in:
lib/copy_ai/errors/http_error.rb

Direct Known Subclasses

ClientError, ServerError

Constant Summary collapse

JSON_CONTENT_TYPE_REGEXP =
%r{application/(problem\+|)json}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response:) ⇒ HTTPError

Returns a new instance of HTTPError.

[View source]

10
11
12
13
14
# File 'lib/copy_ai/errors/http_error.rb', line 10

def initialize(response:)
  super(error_message(response))
  @response = response
  @code = response.code
end

Instance Attribute Details

#codeObject (readonly)

Returns the value of attribute code.


8
9
10
# File 'lib/copy_ai/errors/http_error.rb', line 8

def code
  @code
end

#responseObject (readonly)

Returns the value of attribute response.


8
9
10
# File 'lib/copy_ai/errors/http_error.rb', line 8

def response
  @response
end

Instance Method Details

#error_message(response) ⇒ Object

[View source]

16
17
18
19
20
21
22
# File 'lib/copy_ai/errors/http_error.rb', line 16

def error_message(response)
  if json?(response)
    message_from_json_response(response)
  else
    response.message
  end
end

#json?(response) ⇒ Boolean

Returns:

  • (Boolean)
[View source]

37
38
39
# File 'lib/copy_ai/errors/http_error.rb', line 37

def json?(response)
  JSON_CONTENT_TYPE_REGEXP === response["content-type"]
end

#message_from_json_response(response) ⇒ Object

[View source]

24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/copy_ai/errors/http_error.rb', line 24

def message_from_json_response(response)
  response_object = JSON.parse(response.body)
  if response_object.key?("title") && response_object.key?("detail")
    "#{response_object.fetch("title")}: #{response_object.fetch("detail")}"
  elsif response_object.key?("error")
    response_object.fetch("error")
  elsif response_object["errors"].instance_of?(Array)
    response_object.fetch("errors").map { |error| error.fetch("message") }.join(", ")
  else
    response.message
  end
end