Handling Errors

Elements client libraries would raise exceptions when an error occurs, such as failed charge, parameter validation failure, authentication error and other network issues. You can follow the following code sample to gracefully handle all possible API exceptions.

begin
  # Access Elements resources, e.g., Elements::Charge.create
rescue Elements::CardError => e
  puts "Error code: #{e.error.code}"
  puts "Debug trace id: #{e.error.trace_id}"
  puts "Error message: #{e.error.message}"
  puts "Decline code: #{e.error.decline_code}"
  puts "Psp reference id: #{e.error.psp_reference}"
rescue Elements::InvalidRequestError => e
  # Request contained invalid parameters
    puts "Invalid param: #{e.error.param}"
rescue Elements::IdempotencyError => e
  # Request conflicted with another idempotent request
rescue Elements::APIConnectionError => e
  # Network error occurred during communication with Elements
rescue Elements::GenericAPIError => e
  # Show a generic error message, this error should be rare,
  # and please reach out to us if you stumbled upon this
rescue Elements::RateLimitError => e
  # Too many requests were made in a short time frame,
  # The Ruby client already handles automatic retries
  # with exponential backoff for you.
rescue Elements::AuthenticationError => e
  # You may have an invalid API key
rescue Elements::PermissionError => e
  # You don't have the permission on your API key to perform this operation
end
try:
  # Access Elements resources, e.g., Elements::Charge.create
  pass
except elements.errors.CardError as e:
  print("Error code: %s" % e.code)
  print("Debug trace id: %s" % e.trace_id)
  print("Error message: %s" % e.message)
  print("Decline code: %s" % e.decline_code)
  print("Psp reference id: %s" % e.psp_reference)
except elements.errors.InvalidRequestError as e:
   # Request contained invalid parameters
  print("Invalid param: %s" % e.param)
except elements.errors.IdempotencyError as e:
    # Request conflicted with another idempotent request
    pass
except elements.errors.APIConnectionError as e:
  # Network error occurred during communication with Elements
    pass
except elements.errors.AuthenticationError as e:
  # You may have an invalid API key
  pass
except elements.errors.PermissionError as e:
  # You don't have the permission on your API key to perform this operation
  pass
except elements.errors.RateLimitError as e:
  # Too many requests were made in a short time frame,
  # The Ruby client already handles automatic retries
  # with exponential backoff for you.
  pass
except elements.errors.GenericAPIError as e:
  # Show a generic error message, this error should be rare,
  # and please reach out to us if you stumbled upon this
  pass