API Error Codes

Understanding and handling API errors.


Error Response Format

All API errors return a consistent JSON format:

{
  "message": "Human-readable error message",
  "errors": {
    "field_name": ["Specific error for this field"]
  }
}

HTTP Status Codes

Success Codes

Code Description
200 Request successful
201 Resource created
204 Request successful, no content returned

Client Error Codes

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

Server Error Codes

Code Description
500 Internal Server Error
502 Bad Gateway
503 Service Unavailable

Common Errors

401 Unauthorized

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.


403 Forbidden

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.


404 Not Found

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.


422 Validation Error

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."]
  }
}

429 Rate Limited

{
  "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.


500 Server Error

{
  "message": "An unexpected error occurred. Please try again."
}

Solution: Retry the request. If persistent, contact support.


Handling Errors

PHP Example

$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']);
    }
}

JavaScript Example

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);
}

Validation Rules

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

Best Practices

1. Check Status Codes First

Always check HTTP status code before parsing response body.

2. Handle Rate Limits Gracefully

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');
}

3. Log Errors for Debugging

Log full error responses to help diagnose issues:

Log::error('NordicCDN API Error', [
    'status' => $response->status(),
    'body' => $response->json(),
    'request' => $data
]);

4. Validate Before Sending

Validate data client-side before API requests to reduce 422 errors.