Skip to main content

Error Handling

Learn how to handle errors from the Uplef API.

Error Response Format​

All API errors follow this consistent format:

{
"success": false,
"error": "ERROR_CODE",
"message": "Human-readable error description",
"errors": [
{ "field": "amount", "message": "Amount must be a positive number" }
]
}
FieldDescription
successAlways false for errors
errorMachine-readable error code
messageHuman-readable description
errorsArray of field-level errors (for validation errors)

HTTP Status Codes​

StatusMeaningWhen It Occurs
200SuccessRequest completed successfully
201CreatedResource created successfully
400Bad RequestValidation failed or invalid request
401UnauthorizedInvalid or missing API credentials
403ForbiddenAPI key lacks required permission
404Not FoundResource doesn't exist
429Too Many RequestsRate limit exceeded
500Internal Server ErrorServer-side error (contact support)

Error Codes Reference​

Authentication Errors (401)​

CodeDescriptionSolution
UNAUTHORIZEDInvalid API credentialsCheck your API key and secret are correct
INVALID_API_KEYAPI key not foundVerify the API key exists in your dashboard
INVALID_API_SECRETAPI secret doesn't matchRegenerate API credentials
API_KEY_DISABLEDAPI key has been disabledEnable the key or generate a new one

Permission Errors (403)​

CodeDescriptionSolution
FORBIDDENMissing required permissionGrant the required permission to your API key
PERMISSION_DENIEDAction not allowedCheck API key permissions in dashboard

Validation Errors (400)​

CodeDescriptionSolution
VALIDATION_FAILEDRequest validation failedCheck the errors array for specific field errors
INVALID_AMOUNTAmount must be positiveProvide a positive number
INVALID_CURRENCYUnsupported currencyUse USD (only supported currency)
INVALID_EMAILInvalid email formatProvide a valid email address
INVALID_PHONEInvalid phone numberProvide a valid 10-digit phone number
INVALID_URLInvalid URL formatProvide a valid URL

Order Errors (400/404)​

CodeDescriptionSolution
ORDER_NOT_FOUNDOrder doesn't existVerify the orderId is correct
ORDER_EXPIREDOrder has expiredCreate a new order
ORDER_ALREADY_PAIDOrder already completedCannot modify completed orders
ORDER_CANCELLEDOrder was cancelledCreate a new order
INVALID_STATUSInvalid status transitionCheck current order status

Transaction Errors (400)​

CodeDescriptionSolution
PAYMENT_FAILEDPayment processing failedCheck failureReason for details
GATEWAY_ERRORPayment gateway errorRetry or try a different payment method
INSUFFICIENT_FUNDSCustomer has insufficient fundsCustomer should add funds
PAYMENT_DECLINEDPayment was declinedCustomer should try a different card/method

Refund Errors (400)​

CodeDescriptionSolution
REFUND_NOT_ALLOWEDTransaction cannot be refundedOnly successful payments can be refunded
REFUND_AMOUNT_EXCEEDEDRefund exceeds original amountReduce refund amount
REFUND_ALREADY_PROCESSEDRefund already processedCheck refund status

Rate Limit Errors (429)​

CodeDescriptionSolution
RATE_LIMITEDToo many requestsWait and retry with exponential backoff

Handling Errors in Code​

JavaScript/Node.js​

async function createOrder(orderData) {
try {
const response = await fetch('https://api.uplef.com/api/v1/orders', {
method: 'POST',
headers: {
'X-API-Key': process.env.UPLEF_API_KEY,
'X-API-Secret': process.env.UPLEF_API_SECRET,
'Content-Type': 'application/json',
},
body: JSON.stringify(orderData),
});

const data = await response.json();

if (!response.ok) {
// Handle specific error codes
switch (data.error) {
case 'VALIDATION_FAILED':
console.error('Validation errors:', data.errors);
throw new ValidationError(data.message, data.errors);

case 'UNAUTHORIZED':
console.error('Authentication failed');
throw new AuthError('Invalid API credentials');

case 'RATE_LIMITED':
console.error('Rate limited, retry after:', response.headers.get('X-RateLimit-Reset'));
throw new RateLimitError(data.message);

default:
throw new ApiError(data.error, data.message);
}
}

return data;
} catch (error) {
if (error instanceof ApiError) {
throw error;
}
// Network error
console.error('Network error:', error);
throw new NetworkError('Failed to connect to Uplef API');
}
}

Python​

import requests
from requests.exceptions import RequestException

class UplefError(Exception):
def __init__(self, code, message):
self.code = code
self.message = message
super().__init__(message)

def create_order(order_data):
try:
response = requests.post(
'https://api.uplef.com/api/v1/orders',
headers={
'X-API-Key': os.environ['UPLEF_API_KEY'],
'X-API-Secret': os.environ['UPLEF_API_SECRET'],
},
json=order_data,
timeout=30,
)

data = response.json()

if not response.ok:
if data.get('error') == 'VALIDATION_FAILED':
raise UplefError('VALIDATION_FAILED', data.get('errors', []))
elif data.get('error') == 'RATE_LIMITED':
# Implement retry with backoff
raise UplefError('RATE_LIMITED', 'Too many requests')
else:
raise UplefError(data.get('error'), data.get('message'))

return data

except RequestException as e:
raise UplefError('NETWORK_ERROR', f'Failed to connect: {e}')

Retry Strategy​

For transient errors (5xx, network errors, rate limits), implement exponential backoff:

async function withRetry(fn, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
if (!shouldRetry(error) || attempt === maxRetries - 1) {
throw error;
}

const delay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s
console.log(`Retrying in ${delay}ms...`);
await sleep(delay);
}
}
}

function shouldRetry(error) {
// Retry on network errors, rate limits, and server errors
return (
error.code === 'RATE_LIMITED' ||
error.code === 'NETWORK_ERROR' ||
error.status >= 500
);
}

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

// Usage
const order = await withRetry(() => createOrder({ amount: 100.00 }));

Best Practices​

1. Always Check success Field​

const data = await response.json();

if (!data.success) {
// Handle error
console.error('API Error:', data.error, data.message);
}

2. Log Error Details​

if (!response.ok) {
console.error('Uplef API Error', {
status: response.status,
error: data.error,
message: data.message,
errors: data.errors,
requestId: response.headers.get('X-Request-Id'),
});
}

3. Show User-Friendly Messages​

const ERROR_MESSAGES = {
VALIDATION_FAILED: 'Please check your input and try again',
ORDER_EXPIRED: 'This order has expired. Please create a new order.',
PAYMENT_DECLINED: 'Payment was declined. Please try a different payment method.',
RATE_LIMITED: 'Too many requests. Please wait a moment and try again.',
};

function getUserMessage(errorCode) {
return ERROR_MESSAGES[errorCode] || 'Something went wrong. Please try again.';
}

4. Handle Validation Errors​

if (data.error === 'VALIDATION_FAILED' && data.errors) {
// Display field-specific errors
data.errors.forEach(err => {
const field = document.getElementById(err.field);
if (field) {
field.classList.add('error');
field.nextElementSibling.textContent = err.message;
}
});
}

5. Monitor and Alert​

Set up monitoring for error rates:

// Track error rates
if (!response.ok) {
metrics.increment('uplef.api.error', {
error_code: data.error,
status: response.status,
});

// Alert on high error rates
if (data.error === 'GATEWAY_ERROR') {
alerting.notify('Uplef gateway errors detected');
}
}