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
FieldTypeDescription
codestringMachine-readable error code for programmatic handling
messagestringHuman-readable error description
detailsobject | nullAdditional context about the error (field-specific errors, etc.)

HTTP Status Codes

Status CodeMeaningWhen It Occurs
200 OKSuccessRequest completed successfully
201 CreatedResource CreatedNew resource was created successfully
204 No ContentDeletedResource was successfully deleted
400 Bad RequestValidation ErrorInvalid request body or parameters
401 UnauthorizedAuthentication RequiredMissing or invalid API key
403 ForbiddenPermission DeniedAPI key lacks required permissions/scopes
404 Not FoundResource Not FoundRequested resource does not exist
409 ConflictConflictResource already exists (e.g., duplicate SKU)
422 UnprocessableBusiness Logic ErrorRequest is valid but cannot be processed (e.g., insufficient inventory)
429 Too Many RequestsRate LimitedExceeded rate limit, retry after waiting
500 Server ErrorInternal ErrorSomething went wrong on our end
503 UnavailableService UnavailableAPI is temporarily unavailable for maintenance

Error Codes Reference

Use these error codes to handle specific error scenarios in your integration.

Authentication Errors
CodeHTTP StatusDescription
UNAUTHORIZED401No API key provided or key is invalid
API_KEY_EXPIRED401The API key has expired
API_KEY_REVOKED401The API key has been revoked
FORBIDDEN403API key lacks required scopes for this action
SCOPE_REQUIRED403Specific scope is required (details include required scope)
Validation Errors
CodeHTTP StatusDescription
VALIDATION_ERROR400Request body failed validation
INVALID_PARAMETER400Query parameter is invalid
MISSING_FIELD400Required field is missing
INVALID_FORMAT400Field value has invalid format (e.g., email, UUID)
VALUE_OUT_OF_RANGE400Numeric value is outside allowed range
Resource Errors
CodeHTTP StatusDescription
NOT_FOUND404Requested resource does not exist
CONFLICT409Resource already exists (duplicate)
GONE410Resource has been permanently deleted
Business Logic Errors
CodeHTTP StatusDescription
INSUFFICIENT_INVENTORY422Not enough inventory to fulfill order
ORDER_ALREADY_SHIPPED422Cannot modify order after shipping
ORDER_CANCELLED422Cannot perform action on cancelled order
PRODUCT_INACTIVE422Cannot order inactive product
PAYMENT_FAILED422Payment processing failed
INVALID_TRANSITION422Invalid status transition (e.g., shipped to pending)
Rate Limiting Errors
CodeHTTP StatusDescription
RATE_LIMITED429Rate limit exceeded, check Retry-After header
Server Errors
CodeHTTP StatusDescription
INTERNAL_ERROR500Unexpected server error
SERVICE_UNAVAILABLE503Service temporarily unavailable
GATEWAY_TIMEOUT504Request timed out

Error Handling Examples

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.