Class: DuffelAPI::Middlewares::RaiseDuffelErrors

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/duffel_api/middlewares/raise_duffel_errors.rb

Constant Summary collapse

UNEXPECTED_ERROR_STATUSES =
(501..599).freeze
EXPECTED_ERROR_STATUSES =
(400..500).freeze

Instance Method Summary collapse

Instance Method Details

#on_complete(env) ⇒ Object

Handles a completed (Faraday) request and raises an error, if appropriate

Parameters:

  • env (Faraday::Env)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/duffel_api/middlewares/raise_duffel_errors.rb', line 14

def on_complete(env)
  if !json?(env) || UNEXPECTED_ERROR_STATUSES.include?(env.status)
    response = Response.new(env.response)
    raise DuffelAPI::Errors::Error.new(generate_error_data(env), response)
  end

  if EXPECTED_ERROR_STATUSES.include?(env.status)
    json_body ||= JSON.parse(env.body) unless env.body.empty?
    error = json_body["errors"].first
    error_type = error["type"]

    error_class = error_class_for_type(error_type)

    response = Response.new(env.response)

    raise error_class.new(error, response)
  end
end