Error Handling
Understanding API errors and how to handle them gracefully in your integrations.
Error Response Format
All API errors follow a consistent JSON format, making it easy to handle errors programmatically.
Error Response Structure
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Missing required field: items",
"details": {
"field": "items",
"reason": "required",
"received": null
}
},
"meta": {
"timestamp": "2024-04-17T10:30:00Z",
"requestId": "req_abc123xyz"
}
}Error Object Fields
| Field | Type | Description |
|---|---|---|
| code | string | Machine-readable error code for programmatic handling |
| message | string | Human-readable error description |
| details | object | null | Additional context about the error (field-specific errors, etc.) |
HTTP Status Codes
| Status Code | Meaning | When It Occurs |
|---|---|---|
| 200 OK | Success | Request completed successfully |
| 201 Created | Resource Created | New resource was created successfully |
| 204 No Content | Deleted | Resource was successfully deleted |
| 400 Bad Request | Validation Error | Invalid request body or parameters |
| 401 Unauthorized | Authentication Required | Missing or invalid API key |
| 403 Forbidden | Permission Denied | API key lacks required permissions/scopes |
| 404 Not Found | Resource Not Found | Requested resource does not exist |
| 409 Conflict | Conflict | Resource already exists (e.g., duplicate SKU) |
| 422 Unprocessable | Business Logic Error | Request is valid but cannot be processed (e.g., insufficient inventory) |
| 429 Too Many Requests | Rate Limited | Exceeded rate limit, retry after waiting |
| 500 Server Error | Internal Error | Something went wrong on our end |
| 503 Unavailable | Service Unavailable | API is temporarily unavailable for maintenance |
Error Codes Reference
Use these error codes to handle specific error scenarios in your integration.
Authentication Errors
| Code | HTTP Status | Description |
|---|---|---|
| UNAUTHORIZED | 401 | No API key provided or key is invalid |
| API_KEY_EXPIRED | 401 | The API key has expired |
| API_KEY_REVOKED | 401 | The API key has been revoked |
| FORBIDDEN | 403 | API key lacks required scopes for this action |
| SCOPE_REQUIRED | 403 | Specific scope is required (details include required scope) |
Validation Errors
| Code | HTTP Status | Description |
|---|---|---|
| VALIDATION_ERROR | 400 | Request body failed validation |
| INVALID_PARAMETER | 400 | Query parameter is invalid |
| MISSING_FIELD | 400 | Required field is missing |
| INVALID_FORMAT | 400 | Field value has invalid format (e.g., email, UUID) |
| VALUE_OUT_OF_RANGE | 400 | Numeric value is outside allowed range |
Resource Errors
| Code | HTTP Status | Description |
|---|---|---|
| NOT_FOUND | 404 | Requested resource does not exist |
| CONFLICT | 409 | Resource already exists (duplicate) |
| GONE | 410 | Resource has been permanently deleted |
Business Logic Errors
| Code | HTTP Status | Description |
|---|---|---|
| INSUFFICIENT_INVENTORY | 422 | Not enough inventory to fulfill order |
| ORDER_ALREADY_SHIPPED | 422 | Cannot modify order after shipping |
| ORDER_CANCELLED | 422 | Cannot perform action on cancelled order |
| PRODUCT_INACTIVE | 422 | Cannot order inactive product |
| PAYMENT_FAILED | 422 | Payment processing failed |
| INVALID_TRANSITION | 422 | Invalid status transition (e.g., shipped to pending) |
Rate Limiting Errors
| Code | HTTP Status | Description |
|---|---|---|
| RATE_LIMITED | 429 | Rate limit exceeded, check Retry-After header |
Server Errors
| Code | HTTP Status | Description |
|---|---|---|
| INTERNAL_ERROR | 500 | Unexpected server error |
| SERVICE_UNAVAILABLE | 503 | Service temporarily unavailable |
| GATEWAY_TIMEOUT | 504 | Request timed out |
Error Handling Examples
Best Practice
Always check for both HTTP status codes and error codes. Use the error code for specific handling and the message for logging and debugging.
JavaScript Error Handling
async function createOrder(orderData) {
try {
const response = await fetch('https://gateway.regentherapy.com/api/v1/orders', {
method: 'POST',
headers: {
'X-API-Key': process.env.REGEN_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify(orderData)
});
const result = await response.json();
if (!response.ok) {
// Handle specific error codes
switch (result.error.code) {
case 'INSUFFICIENT_INVENTORY':
throw new Error(`Product out of stock: ${result.error.details?.productId}`);
case 'VALIDATION_ERROR':
throw new Error(`Invalid field: ${result.error.details?.field}`);
case 'RATE_LIMITED':
const retryAfter = response.headers.get('Retry-After');
throw new Error(`Rate limited. Retry after ${retryAfter} seconds`);
case 'UNAUTHORIZED':
throw new Error('Invalid API key');
default:
throw new Error(result.error.message);
}
}
return result.data;
} catch (error) {
console.error('Order creation failed:', error);
throw error;
}
}Python Error Handling
import requests
from typing import Dict, Any
class RegenTherapyError(Exception):
def __init__(self, code: str, message: str, details: Dict = None):
self.code = code
self.message = message
self.details = details
super().__init__(message)
def create_order(order_data: Dict[str, Any]) -> Dict:
response = requests.post(
'https://gateway.regentherapy.com/api/v1/orders',
headers={
'X-API-Key': os.environ['REGEN_API_KEY'],
'Content-Type': 'application/json'
},
json=order_data
)
result = response.json()
if not response.ok:
error = result.get('error', {})
raise RegenTherapyError(
code=error.get('code', 'UNKNOWN'),
message=error.get('message', 'Unknown error'),
details=error.get('details')
)
return result['data']
# Usage
try:
order = create_order(order_data)
except RegenTherapyError as e:
if e.code == 'INSUFFICIENT_INVENTORY':
print(f"Out of stock: {e.details.get('productId')}")
elif e.code == 'RATE_LIMITED':
print("Rate limited, retrying...")
else:
print(f"Error: {e.message}")Troubleshooting Common Errors
401 Unauthorized
Common causes:
- API key is missing from the request headers
- API key is formatted incorrectly (should be
X-API-Key: rg_xxx) - API key has been revoked or deleted
- API key has expired
Solution:
Verify your API key is active in the dashboard and properly included in the X-API-Key header.
403 Forbidden
Common causes:
- API key lacks the required scope for this endpoint
- Attempting to access resources outside your tenant
- Account-level restrictions apply
Solution:
Check the required scopes for the endpoint in the API reference and update your API key permissions.
429 Rate Limited
Common causes:
- Too many requests in a short time period
- Polling too frequently for updates
- Not implementing proper caching
Solution:
Implement exponential backoff, use webhooks instead of polling, and cache responses where appropriate.