Exception: X::HTTPError
- Defined in:
- lib/x/errors/http_error.rb
Overview
Base class for HTTP errors from the X API
Direct Known Subclasses
Constant Summary collapse
- JSON_CONTENT_TYPE_REGEXP =
Regular expression to match JSON content types
%r{application/(problem\+|)json}
Instance Attribute Summary collapse
-
#code ⇒ String
readonly
The HTTP status code.
-
#response ⇒ Net::HTTPResponse
readonly
The HTTP response.
Instance Method Summary collapse
-
#error_message(response) ⇒ String
Get the error message from the response.
-
#initialize(response:) ⇒ HTTPError
constructor
Initialize a new HTTPError.
-
#json?(response) ⇒ Boolean
Check if the response contains JSON.
-
#message_from_json_response(response) ⇒ String
Extract error message from a JSON response.
Constructor Details
#initialize(response:) ⇒ HTTPError
Initialize a new HTTPError
32 33 34 35 36 |
# File 'lib/x/errors/http_error.rb', line 32 def initialize(response:) super((response)) @response = response @code = response.code end |
Instance Attribute Details
#code ⇒ String (readonly)
The HTTP status code
23 24 25 |
# File 'lib/x/errors/http_error.rb', line 23 def code @code end |
#response ⇒ Net::HTTPResponse (readonly)
The HTTP response
16 17 18 |
# File 'lib/x/errors/http_error.rb', line 16 def response @response end |
Instance Method Details
#error_message(response) ⇒ String
Get the error message from the response
45 46 47 48 49 50 51 |
# File 'lib/x/errors/http_error.rb', line 45 def (response) if json?(response) (response) else response. end end |
#json?(response) ⇒ Boolean
Check if the response contains JSON
80 81 82 |
# File 'lib/x/errors/http_error.rb', line 80 def json?(response) JSON_CONTENT_TYPE_REGEXP === response["content-type"] end |
#message_from_json_response(response) ⇒ String
Extract error message from a JSON response
60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/x/errors/http_error.rb', line 60 def (response) response_object = JSON.parse(response.body) if response_object["errors"].instance_of?(Array) response_object.fetch("errors").map { |error| error.fetch("message") }.join(", ") elsif 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") else response. end end |