Error Handling
All Cashela API endpoints return errors in a consistent, machine-readable JSON format. This guide explains the error structure, common error codes, and best practices for handling failures in your integration.
Error Response Structure
All error responses follow this consistent format:
"message" : " Human-readable error description " ,
"doc_url" : " https://docs.cashela.com/errors#error-code "
"request_id" : " req_01HJ3KBCD8E9F0G1H2I3J4K5L6 "
Fields
Field Type Description successboolean Always false for error responses error.codestring Machine-readable error code for programmatic handling error.messagestring Human-readable description, safe to display to users for certain error types error.detailsobject Additional context, field-specific validation errors, or parameters related to the error error.doc_urlstring Link to documentation explaining this error type request_idstring Unique identifier for this request. Include when contacting support
HTTP Status Codes
Cashela uses conventional HTTP status codes to indicate success or failure:
Success Codes (2xx)
Code Status Meaning 200 OK Request succeeded. Response body contains the requested data 201 Created Resource successfully created (e.g., transaction, quotation) 202 Accepted Request accepted for processing but not yet completed 204 No Content Request succeeded with no response body to return
Client Error Codes (4xx)
Code Status Meaning Action 400 Bad Request Malformed request syntax or invalid JSON Fix request format 401 Unauthorized Invalid or missing authentication credentials Verify API credentials 403 Forbidden Valid credentials but insufficient permissions Check IP allowlist or account permissions 404 Not Found Requested resource doesn’t exist Verify endpoint URL and resource ID 405 Method Not Allowed HTTP method not supported for this endpoint Use correct HTTP method (GET, POST, etc.) 409 Conflict Request conflicts with current state (e.g., duplicate idempotency key) Review conflict details and adjust request 422 Unprocessable Entity Request syntax valid but business logic validation failed Fix validation errors in request data 429 Too Many Requests Rate limit exceeded Implement exponential backoff and retry
Server Error Codes (5xx)
Code Status Meaning Action 500 Internal Server Error Unexpected server error Retry with exponential backoff 502 Bad Gateway Upstream service unavailable Retry after brief delay 503 Service Unavailable Temporary service interruption Check status page, retry with backoff 504 Gateway Timeout Request timeout Retry with same idempotency key
Important: 5xx errors are rare and typically transient. Always implement retry logic with exponential backoff for these errors.
Error Types
Cashela categorizes errors into distinct types for easier handling:
Authentication Errors
Error Code Description Resolution UNAUTHORIZEDMissing or invalid API credentials Verify your Business Key and Secret are correct INVALID_API_KEYAPI key format is invalid Check for typos or encoding issues EXPIRED_CREDENTIALSAPI credentials have been revoked Generate new credentials in your dashboard IP_NOT_ALLOWEDRequest from non-allowlisted IP Add your server IP to the allowlist
Validation Errors
Error Code Description Resolution INVALID_INPUTMalformed request body or invalid JSON Check JSON syntax and encoding MISSING_REQUIRED_FIELDRequired parameter not provided Include all required fields INVALID_FIELD_FORMATField value doesn’t match expected format Check field type and format requirements INVALID_DOCUMENTDocument number failed validation Verify document matches country requirements INVALID_EMAILEmail format is invalid Provide valid email address INVALID_PHONEPhone number format is invalid Use E.164 format (e.g., +1234567890) AMOUNT_TOO_LOWAmount below minimum threshold Check minimum amount for payment method AMOUNT_TOO_HIGHAmount exceeds maximum limit Split into multiple transactions or contact support
Transaction Errors
Error Code Description Resolution TRANSACTION_NOT_FOUNDTransaction ID doesn’t exist Verify transaction ID is correct TRANSACTION_EXPIREDTransaction or quotation has expired Create new transaction TRANSACTION_CANCELLEDTransaction was cancelled Create new transaction if needed DUPLICATE_TRANSACTIONTransaction with same external_identifier exists Use unique identifier per transaction INSUFFICIENT_FUNDSAccount balance too low Add funds to your business wallet
Idempotency Errors
Error Code Description Resolution IDEMPOTENCY_CONFLICTSame key used with different request body Use new idempotency key or send identical request IDEMPOTENCY_KEY_REQUIREDPOST request missing Idempotency-Key header Include UUID v4 in header INVALID_IDEMPOTENCY_KEYKey format is invalid Use valid UUID v4 format
Payment Method Errors
Error Code Description Resolution PAYMENT_METHOD_NOT_FOUNDInvalid payment method code Use valid code from Get Payment Methods PAYMENT_METHOD_UNAVAILABLEMethod temporarily unavailable Try alternative method or retry later UNSUPPORTED_COUNTRYCountry not supported for method Choose different country or method UNSUPPORTED_CURRENCYCurrency not supported Check supported currencies
Rate Limiting Errors
Error Code Description Resolution RATE_LIMITEDToo many requests in time window Wait and retry with exponential backoff QUOTA_EXCEEDEDMonthly transaction quota reached Contact support to increase limits
Validation Error Details
When a validation error occurs, the details object contains field-specific error messages:
"code" : " VALIDATION_ERROR " ,
"message" : " Request validation failed " ,
"email" : " Invalid email format. Expected: user@domain.com " ,
"amount" : " Amount must be between 10.00 and 50000.00 MXN " ,
"document_number" : " Invalid format for IFE. Expected pattern: XXXX000000XXXXXX00 " ,
"phone" : " Phone number must be in E.164 format: +521234567890 "
"request_id" : " req_01HJ3KBCD8E9F0G1H2I3J4K5L6 "
Processing validation errors:
function handleValidationErrors ( errorResponse ) {
const { details } = errorResponse . error ;
// Map API field names to form field names
' email ' : ' customerEmail ' ,
' document_number ' : ' documentId ' ,
' amount ' : ' paymentAmount '
// Display errors to user
Object . entries ( details ) . forEach ( ( [ field , message ] ) => {
const formField = fieldMapping [ field ] || field ;
displayFieldError ( formField , message );
Error Handling Best Practices
1. Always Check the Success Field
async function makeApiRequest ( endpoint , data ) {
const response = await fetch ( endpoint , {
headers: getAuthHeaders () ,
body: JSON . stringify ( data )
const result = await response . json ();
// Always check success field, not just HTTP status
throw new CashelaApiError ( result . error , result . request_id );
2. Handle Errors by Code, Not Message
Messages may change; codes are stable:
function handleApiError ( error ) {
// Credential issues - alert operations team
notifyOperations ( ' API credentials invalid ' );
// User input issue - show errors to user
displayValidationErrors ( error . details );
// Temporary - retry with backoff
return scheduleRetry ( error );
case ' INSUFFICIENT_FUNDS ' :
// Balance issue - alert finance team
notifyFinance ( ' Low balance alert ' );
// Unknown error - log and alert
3. Implement Exponential Backoff for Retries
def retry_with_backoff ( func , max_retries= 5 , base_delay= 1 ) :
""" Retry function with exponential backoff and jitter. """
for attempt in range ( max_retries ):
except RetryableError as e:
if attempt == max_retries - 1 :
# Calculate delay with exponential backoff + jitter
delay = base_delay * ( 2 ** attempt)
jitter = random. uniform ( 0 , delay * 0.1 )
total_delay = delay + jitter
print ( f "Attempt {attempt + 1 } failed. Retrying in {total_delay :.2f } s..." )
raise MaxRetriesExceeded ()
def create_transaction () :
response = api. create_deposit ( transaction_data )
if response.error and response.error.code in [ ' RATE_LIMITED ' , ' INTERNAL_ERROR ' , ' SERVICE_UNAVAILABLE ' ] :
raise RetryableError ( response.error )
result = retry_with_backoff ( create_transaction )
4. Log Request IDs for Support
class CashelaApiError extends Error {
constructor ( error , requestId ) {
this . details = error . details ;
this . requestId = requestId ;
// Log for debugging and support
console . error ( ` Cashela API Error [ ${ requestId } ]: ${ error . code } - ${ error . message } ` );
// When contacting support, include the request_id
function reportErrorToSupport ( error ) {
message: ` API error occurred ` ,
requestId: error . requestId , // Always include this
timestamp: new Date () . toISOString ()
5. Display User-Friendly Messages
' VALIDATION_ERROR ' : ' Please check your information and try again. ' ,
' PAYMENT_METHOD_UNAVAILABLE ' : ' This payment method is temporarily unavailable. Please try another option. ' ,
' INSUFFICIENT_FUNDS ' : ' We are unable to process this transaction at the moment. Please try again later. ' ,
' RATE_LIMITED ' : ' Too many attempts. Please wait a moment and try again. ' ,
' INTERNAL_ERROR ' : ' Something went wrong on our end. Please try again in a few minutes. '
function getUserMessage ( errorCode ) {
return USER_MESSAGES [ errorCode ] || ' An unexpected error occurred. Please try again. ' ;
Retryable vs Non-Retryable Errors
Retryable Errors (Safe to Retry)
These errors are transient and may succeed on retry:
Error Code Retry Strategy RATE_LIMITEDWait for Retry-After header or use exponential backoff INTERNAL_ERRORRetry up to 3 times with exponential backoff SERVICE_UNAVAILABLECheck status page, retry with backoff BAD_GATEWAYRetry after 5-10 seconds GATEWAY_TIMEOUTRetry immediately with same idempotency key
Non-Retryable Errors (Do Not Retry)
These errors require fixing the request or account:
Error Code Action Required UNAUTHORIZEDFix credentials VALIDATION_ERRORFix request data INSUFFICIENT_FUNDSAdd funds to account PAYMENT_METHOD_NOT_FOUNDUse valid payment method IDEMPOTENCY_CONFLICTUse new idempotency key