Understanding and handling API errors.
All API errors return a consistent JSON format:
{
"message": "Human-readable error message",
"errors": {
"field_name": ["Specific error for this field"]
}
}
| Code | Description |
|---|---|
200 |
Request successful |
201 |
Resource created |
204 |
Request successful, no content returned |
| Code | Description |
|---|---|
400 |
Bad Request - Invalid request format |
401 |
Unauthorized - Invalid or missing API token |
403 |
Forbidden - Token lacks required permissions |
404 |
Not Found - Resource doesn't exist |
422 |
Unprocessable Entity - Validation failed |
429 |
Too Many Requests - Rate limit exceeded |
| Code | Description |
|---|---|
500 |
Internal Server Error |
502 |
Bad Gateway |
503 |
Service Unavailable |
Missing Token:
{
"message": "Unauthenticated."
}
Solution: Include Authorization: Bearer YOUR_TOKEN header.
Invalid Token:
{
"message": "Invalid API token."
}
Solution: Check token is correct and not revoked.
Insufficient Permissions:
{
"message": "This action is unauthorized."
}
Solution: Use a token with required permissions.
Resource Not Owned:
{
"message": "You do not have access to this resource."
}
Solution: Verify you own the zone or resource.
Zone Not Found:
{
"message": "Zone not found."
}
Solution: Check the zone UUID is correct.
Endpoint Not Found:
{
"message": "Not found."
}
Solution: Verify the API endpoint URL.
Missing Required Field:
{
"message": "The given data was invalid.",
"errors": {
"origin_url": ["The origin url field is required."]
}
}
Invalid Field Format:
{
"message": "The given data was invalid.",
"errors": {
"origin_url": ["The origin url must be a valid URL."]
}
}
Multiple Errors:
{
"message": "The given data was invalid.",
"errors": {
"origin_url": ["The origin url field is required."],
"cache_ttl": ["The cache ttl must be at least 60."]
}
}
{
"message": "Too many requests. Please try again later."
}
Headers:
Retry-After: 60
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1640995200
Solution: Wait until X-RateLimit-Reset timestamp or Retry-After seconds.
{
"message": "An unexpected error occurred. Please try again."
}
Solution: Retry the request. If persistent, contact support.
$response = Http::withToken($token)
->post("https://nordiccdn.com/api/v1/zones", $data);
if ($response->failed()) {
$status = $response->status();
$body = $response->json();
switch ($status) {
case 401:
throw new AuthenticationException($body['message']);
case 422:
throw new ValidationException($body['errors']);
case 429:
$retryAfter = $response->header('Retry-After');
sleep($retryAfter);
// Retry request
break;
default:
throw new ApiException($body['message']);
}
}
try {
const response = await fetch('https://nordiccdn.com/api/v1/zones', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (!response.ok) {
const error = await response.json();
if (response.status === 422) {
// Handle validation errors
console.error('Validation errors:', error.errors);
} else if (response.status === 429) {
// Handle rate limiting
const retryAfter = response.headers.get('Retry-After');
console.log(`Rate limited. Retry after ${retryAfter} seconds`);
} else {
console.error('API error:', error.message);
}
return;
}
const result = await response.json();
console.log('Success:', result);
} catch (err) {
console.error('Network error:', err);
}
Common validation rules for API fields:
| Field | Rules |
|---|---|
origin_url |
Required, valid URL, max 255 chars |
name |
Optional, string, max 100 chars |
cache_ttl |
Integer, min 60, max 31536000 |
zone_type |
One of: cdn, accelerator |
paths |
Array, max 1000 items, valid paths |
Always check HTTP status code before parsing response body.
Implement exponential backoff:
async function apiRequest(url, options, retries = 3) {
for (let i = 0; i < retries; i++) {
const response = await fetch(url, options);
if (response.status === 429) {
const delay = Math.pow(2, i) * 1000;
await new Promise(r => setTimeout(r, delay));
continue;
}
return response;
}
throw new Error('Max retries exceeded');
}
Log full error responses to help diagnose issues:
Log::error('NordicCDN API Error', [
'status' => $response->status(),
'body' => $response->json(),
'request' => $data
]);
Validate data client-side before API requests to reduce 422 errors.