Class: Mercadopago::MPResponse

Inherits:
Hash
  • Object
show all
Defined in:
lib/mercadopago/errors/response.rb

Overview

Backward-compatible Hash wrapper for MercadoPago API responses.

Wraps the raw { status:, response: } hash returned by every MPBase helper. Existing code that reads result[:status] or result[:response] continues to work unchanged.

New code may call #raise_for_status! to get a typed exception or use the convenience accessors #success?, #error_message, #error_causes.

Instance Method Summary collapse

Constructor Details

#initialize(raw = {}, request_id: nil) ⇒ MPResponse

Returns a new instance of MPResponse.

Parameters:

  • raw (Hash) (defaults to: {})

    the raw response hash with :status and :response keys

  • request_id (String, nil) (defaults to: nil)

    value of the x-request-id response header



15
16
17
18
19
# File 'lib/mercadopago/errors/response.rb', line 15

def initialize(raw = {}, request_id: nil)
  super()
  update(raw)
  @request_id = request_id
end

Instance Method Details

#error_causesArray

Returns cause list from the API body.

Returns:

  • (Array)

    cause list from the API body



38
39
40
41
# File 'lib/mercadopago/errors/response.rb', line 38

def error_causes
  body = self[:response] || self['response'] || {}
  body.is_a?(Hash) ? (body['cause'] || body[:cause] || []) : []
end

#error_messageString

Returns human-readable error message from the API body.

Returns:

  • (String)

    human-readable error message from the API body



32
33
34
35
# File 'lib/mercadopago/errors/response.rb', line 32

def error_message
  body = self[:response] || self['response'] || {}
  body.is_a?(Hash) ? (body['message'] || body[:message] || '') : ''
end

#raise_for_status!Object

Raises a typed Mercadopago::MercadoPagoError subclass when the response status is not 2xx.

Raises:



51
52
53
54
55
56
# File 'lib/mercadopago/errors/response.rb', line 51

def raise_for_status!
  return if success?

  body = self[:response] || self['response'] || {}
  raise Mercadopago.build_error(status_code, body)
end

#request_idString?

Returns x-request-id header value.

Returns:

  • (String, nil)

    x-request-id header value



44
45
46
# File 'lib/mercadopago/errors/response.rb', line 44

def request_id
  @request_id
end

#status_codeInteger

Returns HTTP status code.

Returns:

  • (Integer)

    HTTP status code



22
23
24
# File 'lib/mercadopago/errors/response.rb', line 22

def status_code
  self[:status] || self['status'] || 0
end

#success?Boolean

Returns true for 2xx status codes.

Returns:

  • (Boolean)

    true for 2xx status codes



27
28
29
# File 'lib/mercadopago/errors/response.rb', line 27

def success?
  status_code >= 200 && status_code < 300
end