Class: Faraday::ExtendedParseJson

Inherits:
FaradayMiddleware::ParseJson
  • Object
show all
Defined in:
lib/faraday/extended_parse_json.rb

Overview

A middleware to display error messages in the JSON response

Instance Method Summary collapse

Instance Method Details

#exception(env) ⇒ Object



39
40
41
42
43
44
# File 'lib/faraday/extended_parse_json.rb', line 39

def exception(env)
  # NOTE: decide to retry or not, the header is deleted
  #  so it won't be sent to the server
  retries = env.request_headers.delete('X-ParseRubyClient-Retries')
  (retries.to_i.zero? ? Parse::ParseProtocolError : Parse::ParseProtocolRetry)
end

#process_response(env) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/faraday/extended_parse_json.rb', line 5

def process_response(env)
  env[:raw_body] = env[:body] if preserve_raw?(env)

  if env[:status] >= 400
    begin
      data = parse(env[:body]) || {}
    rescue StandardError
      data = {}
    end

    array_codes = [
      Parse::Protocol::ERROR_INTERNAL,
      Parse::Protocol::ERROR_TIMEOUT,
      Parse::Protocol::ERROR_EXCEEDED_BURST_LIMIT
    ]

    error_hash = {
      'error' => "HTTP Status #{env[:status]} Body #{env[:body]}",
      'http_status_code' => env[:status]
    }.merge(data)

    if data['code'] && \
      array_codes.include?(data['code']) && \
      data['code'] == Parse::Protocol::ERROR_EXCEEDED_BURST_LIMIT
      sleep 60
    end

    raise exception(env), error_hash
  else
    data = parse(env[:body]) || {}
    env[:body] = data
  end
end