Error Handling

Understand and handle API errors effectively

Overview

The Connect2Print API uses standard HTTP status codes and structured error responses to communicate problems. This guide helps you understand and handle errors correctly.

Error Response Format

All API errors are returned in the following standard format:

{
  "success": false,
  "error": {
    "code": "validation_error",
    "message": "Invalid input data",
    "details": {
      "email": ["Email format is invalid"],
      "quantity": ["Must be at least 1"]
    }
  }
}

Response Fields:

HTTP Status Codes

The API uses standard HTTP status codes:

2xx - Success

  • 200 OK - Request succeeded
  • 201 Created - Resource was created
  • 204 No Content - Successful deletion

4xx - Client Errors

  • 400 Bad Request - Invalid request or validation error
  • 401 Unauthorized - Missing or invalid authentication
  • 403 Forbidden - Insufficient permissions
  • 404 Not Found - Resource not found
  • 409 Conflict - Conflict with existing resource
  • 422 Unprocessable Entity - Validation error
  • 429 Too Many Requests - Rate limit exceeded

5xx - Server Errors

  • 500 Internal Server Error - Server error
  • 502 Bad Gateway - Gateway error
  • 503 Service Unavailable - Service temporarily unavailable

Error Codes Reference

The API uses the following error codes:

Authentication & Authorization

  • unauthorized - Invalid or missing API key
  • insufficient_permissions - API key lacks required scopes
  • expired_token - API key has expired
  • revoked_token - API key has been revoked

Validation

  • validation_error - Input data is invalid
  • missing_field - Required field is missing
  • invalid_format - Field has wrong format
  • invalid_value - Field value is invalid

Resource Errors

  • not_found - Resource not found
  • duplicate_resource - Resource already exists
  • invalid_state - Operation not allowed in current state
  • resource_locked - Resource is locked

Rate Limiting

  • rate_limit_exceeded - Too many requests

Server Errors

  • server_error - Internal server error
  • service_unavailable - Service temporarily unavailable

Error Examples

Validation Error (400)

HTTP/1.1 400 Bad Request

{
  "success": false,
  "error": {
    "code": "validation_error",
    "message": "Validation failed",
    "details": {
      "email": ["Email format is invalid"],
      "quantity": ["Must be between 1 and 1000"]
    }
  }
}

Unauthorized (401)

HTTP/1.1 401 Unauthorized

{
  "success": false,
  "error": {
    "code": "unauthorized",
    "message": "Invalid API key"
  }
}

Forbidden (403)

HTTP/1.1 403 Forbidden

{
  "success": false,
  "error": {
    "code": "insufficient_permissions",
    "message": "API key lacks required scope: orders:write"
  }
}

Not Found (404)

HTTP/1.1 404 Not Found

{
  "success": false,
  "error": {
    "code": "not_found",
    "message": "Order not found"
  }
}

Rate Limit (429)

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

{
  "success": false,
  "error": {
    "code": "rate_limit_exceeded",
    "message": "Rate limit exceeded. Try again in 60 seconds."
  }
}

Error Handling Best Practices

Follow these best practices when handling API errors:

Check HTTP status code first

Use the HTTP status code to determine error type before parsing response body.

Parse the error code

Use the error.code field to determine the specific error and handle appropriately.

Display user-friendly messages

Don't show raw API error messages to end users. Translate to user-friendly messages.

Log error details

Log the full error response, request details, and context for debugging.

Handle validation errors

For validation errors, show which fields are invalid and why.

Implement retry logic

For 5xx errors and 429, implement retry with exponential backoff.

Monitor error rates

Track error rates over time to identify issues early.

Handle network errors

Handle timeout, connection errors, and other network issues gracefully.

Code Examples

Examples of error handling in different languages:

PHP Error Handling

try {
    $response = makeApiRequest($url, $apiKey);

    if (!$response['success']) {
        $errorCode = $response['error']['code'];
        $errorMessage = $response['error']['message'];

        switch ($errorCode) {
            case 'unauthorized':
                handleUnauthorized();
                break;
            case 'validation_error':
                handleValidationError($response['error']['details']);
                break;
            case 'rate_limit_exceeded':
                handleRateLimit();
                break;
            default:
                handleGenericError($errorMessage);
        }
    }
} catch (Exception $e) {
    error_log("API request failed: " . $e->getMessage());
}

Node.js Error Handling

try {
  const response = await makeApiRequest(url, apiKey);

  if (!response.success) {
    const { code, message, details } = response.error;

    switch (code) {
      case 'unauthorized':
        handleUnauthorized();
        break;
      case 'validation_error':
        handleValidationError(details);
        break;
      case 'rate_limit_exceeded':
        await handleRateLimit();
        break;
      default:
        handleGenericError(message);
    }
  }
} catch (error) {
  console.error('API request failed:', error);
}

Python Error Handling

try:
    response = make_api_request(url, api_key)

    if not response['success']:
        error = response['error']
        code = error['code']
        message = error['message']

        if code == 'unauthorized':
            handle_unauthorized()
        elif code == 'validation_error':
            handle_validation_error(error.get('details'))
        elif code == 'rate_limit_exceeded':
            handle_rate_limit()
        else:
            handle_generic_error(message)

except Exception as e:
    print(f'API request failed: {e}')

Debugging Tips

Tips for debugging API issues:

Use Request ID

Each response includes an X-Request-Id header. Save this for support requests.

Check API Logs

Review your API request logs in the admin panel to see request/response details.

Test in Postman/cURL

Isolate the problem by testing the same request in Postman or cURL.

Verify Headers

Ensure all required headers are set correctly (Authorization, Content-Type, etc.).

Validate JSON

Ensure request body is valid JSON without syntax errors.

Check API Status

If experiencing widespread errors, check the API status page for known issues.

Next Steps

Explore related topics:

Rate Limiting

Learn how to handle 429 errors specifically

Rate Limiting

Authentication

Understand 401 and 403 errors in depth

Authentication

API Reference

See which errors each endpoint can return

API Reference

Code Examples

See more advanced error handling examples

Code Examples