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" }
]
}
| Field | Description |
|---|---|
success | Always false for errors |
error | Machine-readable error code |
message | Human-readable description |
errors | Array of field-level errors (for validation errors) |
HTTP Status Codes
| Status | Meaning | When It Occurs |
|---|---|---|
200 | Success | Request completed successfully |
201 | Created | Resource created successfully |
400 | Bad Request | Validation failed or invalid request |
401 | Unauthorized | Invalid or missing API credentials |
403 | Forbidden | API key lacks required permission |
404 | Not Found | Resource doesn't exist |
429 | Too Many Requests | Rate limit exceeded |
500 | Internal Server Error | Server-side error (contact support) |
Error Codes Reference
Authentication Errors (401)
| Code | Description | Solution |
|---|---|---|
UNAUTHORIZED | Invalid API credentials | Check your API key and secret are correct |
INVALID_API_KEY | API key not found | Verify the API key exists in your dashboard |
INVALID_API_SECRET | API secret doesn't match | Regenerate API credentials |
API_KEY_DISABLED | API key has been disabled | Enable the key or generate a new one |
Permission Errors (403)
| Code | Description | Solution |
|---|---|---|
FORBIDDEN | Missing required permission | Grant the required permission to your API key |
PERMISSION_DENIED | Action not allowed | Check API key permissions in dashboard |
Validation Errors (400)
| Code | Description | Solution |
|---|---|---|
VALIDATION_FAILED | Request validation failed | Check the errors array for specific field errors |
INVALID_AMOUNT | Amount must be positive | Provide a positive number |
INVALID_CURRENCY | Unsupported currency | Use USD (only supported currency) |
INVALID_EMAIL | Invalid email format | Provide a valid email address |
INVALID_PHONE | Invalid phone number | Provide a valid 10-digit phone number |
INVALID_URL | Invalid URL format | Provide a valid URL |
Order Errors (400/404)
| Code | Description | Solution |
|---|---|---|
ORDER_NOT_FOUND | Order doesn't exist | Verify the orderId is correct |
ORDER_EXPIRED | Order has expired | Create a new order |
ORDER_ALREADY_PAID | Order already completed | Cannot modify completed orders |
ORDER_CANCELLED | Order was cancelled | Create a new order |
INVALID_STATUS | Invalid status transition | Check current order status |
Transaction Errors (400)
| Code | Description | Solution |
|---|---|---|
PAYMENT_FAILED | Payment processing failed | Check failureReason for details |
GATEWAY_ERROR | Payment gateway error | Retry or try a different payment method |
INSUFFICIENT_FUNDS | Customer has insufficient funds | Customer should add funds |
PAYMENT_DECLINED | Payment was declined | Customer should try a different card/method |
Refund Errors (400)
| Code | Description | Solution |
|---|---|---|
REFUND_NOT_ALLOWED | Transaction cannot be refunded | Only successful payments can be refunded |
REFUND_AMOUNT_EXCEEDED | Refund exceeds original amount | Reduce refund amount |
REFUND_ALREADY_PROCESSED | Refund already processed | Check refund status |
Rate Limit Errors (429)
| Code | Description | Solution |
|---|---|---|
RATE_LIMITED | Too many requests | Wait 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');
}
}