Class: Restforce::Middleware::RaiseError

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/restforce/middleware/raise_error.rb

Constant Summary collapse

ERROR_CODE_MATCHER =
/\A[A-Z_]+\z/

Instance Method Summary collapse

Instance Method Details

#bodyObject



44
45
46
47
48
49
50
51
52
53
# File 'lib/restforce/middleware/raise_error.rb', line 44

def body
  @body = (@env[:body].is_a?(Array) ? @env[:body].first : @env[:body])

  case @body
  when Hash
    @body
  else
    { 'errorCode' => '(error code missing)', 'message' => @body }
  end
end

#call(env) ⇒ Object

Required for Faraday versions pre-v1.2.0 which do not include an implementation of ‘#call` by default



7
8
9
10
11
12
# File 'lib/restforce/middleware/raise_error.rb', line 7

def call(env)
  on_request(env) if respond_to?(:on_request)
  @app.call(env).on_complete do |environment|
    on_complete(environment) if respond_to?(:on_complete)
  end
end

#exception_class_for_error_code(error_code) ⇒ Object



65
66
67
68
69
# File 'lib/restforce/middleware/raise_error.rb', line 65

def exception_class_for_error_code(error_code)
  return Restforce::ResponseError unless ERROR_CODE_MATCHER.match?(error_code)

  Restforce::ErrorCode.get_exception_class(error_code)
end

#messageObject



37
38
39
40
41
42
# File 'lib/restforce/middleware/raise_error.rb', line 37

def message
  message = "#{body['errorCode']}: #{body['message']}"
  message << "\nRESPONSE: #{JSON.dump(@env[:body])}"
rescue StandardError
  message # if JSON.dump fails, return message without extra detail
end

#on_complete(env) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/restforce/middleware/raise_error.rb', line 14

def on_complete(env)
  @env = env
  case env[:status]
  when 300
    raise Restforce::MatchesMultipleError.new(
      "300: The external ID provided matches more than one record",
      response_values
    )
  when 401
    raise Restforce::UnauthorizedError.new(message, response_values)
  when 404
    raise Restforce::NotFoundError.new(message, response_values)
  when 413
    raise Restforce::EntityTooLargeError.new(
      "413: Request Entity Too Large",
      response_values
    )
  when 400...600
    klass = exception_class_for_error_code(body['errorCode'])
    raise klass.new(message, response_values)
  end
end

#response_valuesObject



55
56
57
58
59
60
61
# File 'lib/restforce/middleware/raise_error.rb', line 55

def response_values
  {
    status: @env[:status],
    headers: @env[:response_headers],
    body: @env[:body]
  }
end