---
title: "Error Handling"
description: "Understand API error responses and how to handle them in your applications"
keywords: [errors, error handling, status codes, exceptions, api errors]
---

# Error Handling

The TraceRTM API uses standard HTTP status codes and structured error responses to communicate errors clearly.

## Error Response Format

All error responses follow this structure:

```json
{
  "error": {
    "code": "error_code",
    "message": "Human-readable error message",
    "details": [
      {
        "field": "field_name",
        "message": "Field-specific error message"
      }
    ]
  },
  "meta": {
    "request_id": "req_xyz789",
    "timestamp": "2025-01-20T10:30:00Z"
  }
}
```

## HTTP Status Codes

| Code | Meaning | Description |
|------|---------|-------------|
| `200` | OK | Request succeeded |
| `201` | Created | Resource created successfully |
| `204` | No Content | Delete succeeded (no response body) |
| `400` | Bad Request | Invalid request parameters |
| `401` | Unauthorized | Authentication required or invalid |
| `403` | Forbidden | Insufficient permissions |
| `404` | Not Found | Resource doesn't exist |
| `409` | Conflict | Version conflict or duplicate |
| `422` | Unprocessable Entity | Validation error |
| `429` | Too Many Requests | Rate limit exceeded |
| `500` | Internal Server Error | Server error |
| `503` | Service Unavailable | Service temporarily unavailable |

## Common Error Codes

### Authentication Errors

#### `authentication_required`

```json
{
  "error": {
    "code": "authentication_required",
    "message": "Authorization required"
  }
}
```

**Solution**: Include valid authentication credentials.

#### `invalid_api_key`

```json
{
  "error": {
    "code": "invalid_api_key",
    "message": "Invalid API key"
  }
}
```

**Solution**: Verify API key is correct and not revoked.

#### `token_expired`

```json
{
  "error": {
    "code": "token_expired",
    "message": "Token has expired",
    "refresh_url": "/api/auth/refresh"
  }
}
```

**Solution**: Refresh the access token.

### Validation Errors

#### `validation_error`

```json
{
  "error": {
    "code": "validation_error",
    "message": "Invalid request parameters",
    "details": [
      {
        "field": "title",
        "message": "Title is required"
      },
      {
        "field": "status",
        "message": "Status must be one of: draft, active, review"
      }
    ]
  }
}
```

**Solution**: Fix validation errors in request body.

### Resource Errors

#### `not_found`

```json
{
  "error": {
    "code": "not_found",
    "message": "Item not found"
  }
}
```

**Solution**: Verify resource ID exists.

#### `forbidden`

```json
{
  "error": {
    "code": "forbidden",
    "message": "Insufficient permissions"
  }
}
```

**Solution**: Check API key or token permissions.

### Rate Limiting

#### `rate_limit_exceeded`

```json
{
  "error": {
    "code": "rate_limit_exceeded",
    "message": "Rate limit exceeded. Please retry after 2025-01-20T10:31:00Z",
    "retry_after": 60
  }
}
```

**Solution**: Wait for rate limit to reset or upgrade plan.

## Error Handling Examples

### Python

```python
from tracertm import TraceRTM
from tracertm.exceptions import (
    APIError,
    AuthenticationError,
    NotFoundError,
    RateLimitError,
    ValidationError
)

client = TraceRTM(api_key="rtm_live_abc123...")

try:
    item = client.items.get("item_abc123")
except NotFoundError:
    print("Item not found")
except AuthenticationError:
    print("Authentication failed. Check your API key.")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
    time.sleep(e.retry_after)
except ValidationError as e:
    print(f"Validation error: {e.message}")
    for detail in e.details:
        print(f"  - {detail.field}: {detail.message}")
except APIError as e:
    print(f"API error: {e.code} - {e.message}")
```

### JavaScript

```javascript
const { TraceRTM, APIError, NotFoundError, RateLimitError } = require('@tracertm/sdk');

const client = new TraceRTM({ apiKey: 'rtm_live_abc123...' });

try {
  const item = await client.items.get('item_abc123');
} catch (error) {
  if (error instanceof NotFoundError) {
    console.log('Item not found');
  } else if (error instanceof RateLimitError) {
    console.log(`Rate limited. Retry after ${error.retryAfter} seconds`);
    await sleep(error.retryAfter * 1000);
  } else if (error instanceof APIError) {
    console.log(`API error: ${error.code} - ${error.message}`);
    if (error.details) {
      error.details.forEach(detail => {
        console.log(`  - ${detail.field}: ${detail.message}`);
      });
    }
  } else {
    console.error('Unexpected error:', error);
  }
}
```

### Retry Logic

```python
import time
from tracertm.exceptions import RateLimitError, APIError

def make_request_with_retry(client, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.items.get("item_abc123")
        except RateLimitError as e:
            if attempt < max_retries - 1:
                wait_time = e.retry_after or (2 ** attempt)
                print(f"Rate limited. Waiting {wait_time} seconds...")
                time.sleep(wait_time)
                continue
            raise
        except APIError as e:
            if e.status_code >= 500 and attempt < max_retries - 1:
                # Retry on server errors
                time.sleep(2 ** attempt)
                continue
            raise
    
    raise Exception("Max retries exceeded")
```

## Error Response Headers

Error responses include helpful headers:

```http
HTTP/1.1 429 Too Many Requests
Retry-After: 60
X-RateLimit-Limit: 300
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1704067200
X-Request-ID: req_xyz789
```

### Request ID

Every response includes a request ID for support:

```python
response = requests.get(url, headers=headers)
request_id = response.headers.get('X-Request-ID')

if response.status_code != 200:
    print(f"Error occurred. Request ID: {request_id}")
    # Include request_id when contacting support
```

## Best Practices

### 1. Always Handle Errors

```python
# ✅ Good: Error handling
try:
    item = client.items.get("item_abc123")
except NotFoundError:
    handle_not_found()
except APIError as e:
    log_error(e)
    raise

# ❌ Bad: No error handling
item = client.items.get("item_abc123")  # May crash
```

### 2. Log Error Details

```python
import logging

logger = logging.getLogger(__name__)

try:
    item = client.items.get("item_abc123")
except APIError as e:
    logger.error(
        f"API error: {e.code} - {e.message}",
        extra={
            "request_id": e.request_id,
            "status_code": e.status_code,
            "details": e.details
        }
    )
    raise
```

### 3. Implement Retry Logic

```python
def retry_on_server_error(func, max_retries=3):
    for attempt in range(max_retries):
        try:
            return func()
        except APIError as e:
            if e.status_code >= 500 and attempt < max_retries - 1:
                time.sleep(2 ** attempt)
                continue
            raise
    raise Exception("Max retries exceeded")
```

### 4. Validate Before Sending

```python
# ✅ Good: Validate before API call
def create_item(title, description):
    if not title or len(title) > 255:
        raise ValueError("Invalid title")
    
    return client.items.create(title=title, description=description)

# ❌ Bad: Let API validate
def create_item(title, description):
    return client.items.create(title=title, description=description)
    # May fail with validation error
```

## Error Codes Reference

| Code | HTTP Status | Description |
|------|-------------|-------------|
| `authentication_required` | 401 | Missing or invalid auth |
| `invalid_api_key` | 401 | Invalid API key |
| `token_expired` | 401 | Token expired |
| `forbidden` | 403 | Insufficient permissions |
| `not_found` | 404 | Resource not found |
| `validation_error` | 422 | Invalid request data |
| `rate_limit_exceeded` | 429 | Too many requests |
| `internal_error` | 500 | Server error |
| `service_unavailable` | 503 | Service temporarily down |

## Related Documentation

- [Authentication](/docs/api-reference/authentication) - Authentication errors
- [Rate Limiting](/docs/api-reference/authentication/rate-limiting) - Rate limit errors
- [API Reference](./01-overview) - General API information
