Skip to main content

Error Handling

Understanding and handling API errors.

HTTP Status Codes

CodeMeaningAction
200SuccessRequest completed
201CreatedResource created
400Bad RequestCheck request format
401UnauthorizedToken expired or invalid
403ForbiddenInsufficient permissions
404Not FoundResource doesn't exist
422Validation ErrorFix request data
429Rate LimitedSlow down requests
500Server ErrorRetry or contact support

Error Response Format

All errors return a consistent JSON structure:

{
"statusCode": 422,
"error": "Unprocessable Entity",
"message": "Validation failed",
"details": [
{
"field": "consumer.email",
"message": "\"email\" must be a valid email"
}
]
}

Handling Errors in Code

interface ApiError {
statusCode: number;
error: string;
message: string;
details?: Array<{
field: string;
message: string;
}>;
}

async function createOrder(order: OrderPayload): Promise<Order> {
const response = await fetch("https://na1-prod.okcapsule.app/v2/orders", {
method: "POST",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
body: JSON.stringify(order),
});

if (!response.ok) {
const error: ApiError = await response.json();

switch (response.status) {
case 401:
// Token expired - refresh and retry
await refreshToken();
return createOrder(order);

case 422:
// Validation error - log details
console.error("Validation errors:", error.details);
throw new Error(`Validation failed: ${error.message}`);

case 429:
// Rate limited - wait and retry
const retryAfter = response.headers.get("Retry-After") || "60";
await sleep(parseInt(retryAfter) * 1000);
return createOrder(order);

default:
throw new Error(`API error: ${error.message}`);
}
}

const data = await response.json();
return data.order;
}

Common Validation Errors

Order Structure Errors

These are the most common errors when creating orders:

ErrorCauseFix
"consumer" is requiredMissing consumer objectAdd consumer with either id or first_name/last_name
"shipping_address" is requiredMissing address objectAdd shipping_address with required fields
"order_lines" is requiredMissing order linesAdd order_lines array with at least one item
"order_lines" must contain at least 1 itemsEmpty order lines arrayInclude at least one order line
"pouches" is requiredMissing pouches in order lineAdd pouches array to each order line
Either pack_id or contents requiredPouch has neitherAdd either pack_id OR contents (not both)
"client_product_id" is requiredMissing product in contentsAdd client_product_id to each content item

Consumer Errors

ErrorCauseFix
"last_name" is requiredProvided first_name without last_nameInclude both first_name and last_name
"id" must be a valid GUIDInvalid consumer ID formatUse valid UUID format
Consumer not foundConsumer ID doesn't existVerify consumer exists with GET /v2/consumers/{id}
"email" must be a valid emailInvalid email formatCheck email syntax
"phone_number" length must be less than or equal to 15Phone too longUse E.164 format (+12125551234)
Consumer Pattern

You must provide either:

  • consumer.id (existing consumer) OR
  • consumer.first_name + consumer.last_name (new consumer)

Don't mix both patterns.

Address Errors

ErrorCauseFix
"address1" is requiredMissing street addressAdd address1 field
"city" is requiredMissing cityAdd city field
"country_name" is requiredMissing countryAdd country_name field
Address line 1 must be less than 100 charactersAddress too longShorten to 100 chars max
City must be less than 50 charactersCity name too longShorten to 50 chars max

Product Errors

ErrorCauseFix
"client_product_id" must be a valid GUIDInvalid product ID formatUse valid UUID format
The following client products are inactive and cannot be ordered: [names]Product is inactiveUse only products where active: true
The following OKC products are inactive and cannot be ordered: [names]Underlying OKC product discontinuedContact OK Capsule support
Product not foundProduct ID doesn't existVerify product with GET /v2/products/{id}
Product does not belong to clientWrong client's productUse products from your own catalog

Packaging Asset Group Errors

ErrorCauseFix
No Packaging Asset Group ID found for the order lineMissing PAG configurationContact OK Capsule to configure your packaging
Order set to "Needs Changes" statusPAG is not "Active"Contact OK Capsule to approve your packaging design
Packaging Asset Groups

Packaging Asset Groups (PAGs) define your packaging design. Orders require an active PAG, which is typically configured during client onboarding. If you see PAG errors, contact OK Capsule support.

Order Status Errors

ErrorCauseFix
Order cannot be modifiedOrder status is past "Pending"/"On Hold"Orders can only be modified before acceptance
Order cannot be canceledOrder already in productionContact support to cancel accepted orders

Authentication Errors

401 Unauthorized

{
"statusCode": 401,
"error": "Unauthorized",
"message": "Token expired"
}

Solution: Refresh your access token:

async function refreshToken(): Promise<string> {
const response = await fetch(
"https://na1-prod.okcapsule.app/v2/authentication/refresh-token",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refresh_token }),
}
);

const data = await response.json();
return data.access_token;
}

403 Forbidden

{
"statusCode": 403,
"error": "Forbidden",
"message": "Insufficient permissions"
}

Solution: Your user lacks the required permission scope. Contact your admin to update role permissions.

Rate Limiting

When rate limited, the API returns:

HTTP/1.1 429 Too Many Requests
Retry-After: 60

Best practices:

  • Implement exponential backoff
  • Cache responses when possible
  • Batch operations where supported
async function withRetry<T>(fn: () => Promise<T>, maxRetries = 3): Promise<T> {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
if (error.status === 429 && attempt < maxRetries - 1) {
const delay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s
await sleep(delay);
continue;
}
throw error;
}
}
throw new Error("Max retries exceeded");
}

Debugging Tips

  1. Check the full error response - Details array contains field-specific errors
  2. Validate before sending - Use the field constraints from Create Orders
  3. Test in Stage first - Use the stage environment for development
  4. Log request/response - Include correlation IDs for support tickets

Getting Help

If you encounter persistent errors:

  1. Check the Interactive API Docs for endpoint details
  2. Verify your request matches the expected schema
  3. Contact OK Capsule support with:
    • Request URL and method
    • Request body (redact sensitive data)
    • Full error response
    • Timestamp of the request