# Error Handling

Comprehensive guide to handling errors in the AIDP API.

## Error Response Format

All API errors follow a consistent format:

```json
{
  "error": "Error message",
  "code": "ERROR_CODE",
  "details": {
    "field": "Additional context"
  },
  "requestId": "req_abc123"
}
```

***

## HTTP Status Codes

### 2xx Success

* **200 OK**: Request successful
* **201 Created**: Resource created successfully

### 4xx Client Errors

* **400 Bad Request**: Invalid request parameters
* **401 Unauthorized**: Missing or invalid API key
* **403 Forbidden**: Insufficient permissions
* **404 Not Found**: Resource doesn't exist
* **429 Too Many Requests**: Rate limit exceeded

### 5xx Server Errors

* **500 Internal Server Error**: Server-side error
* **503 Service Unavailable**: Temporary service disruption

***

## Common Errors

### Authentication Errors

**401 Unauthorized**

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

**Solution**: Check your API key is correct and active.

### Validation Errors

**400 Bad Request**

```json
{
  "error": "Validation failed",
  "code": "VALIDATION_ERROR",
  "details": {
    "query": "Query is required",
    "location.lat": "Must be between -90 and 90"
  }
}
```

**Solution**: Fix the invalid fields listed in `details`.

### Rate Limit Errors

**429 Too Many Requests**

```json
{
  "error": "Rate limit exceeded",
  "code": "RATE_LIMIT_EXCEEDED",
  "retryAfter": 3600
}
```

**Solution**: Wait `retryAfter` seconds before retrying.

### Not Found Errors

**404 Not Found**

```json
{
  "error": "Business not found",
  "code": "BUSINESS_NOT_FOUND",
  "details": {
    "businessId": "biz_invalid123"
  }
}
```

**Solution**: Verify the resource ID is correct.

***

## Error Handling Best Practices

### 1. Always Check Status Codes

```javascript
const response = await fetch(url, options);

if (!response.ok) {
  const error = await response.json();
  throw new APIError(error.error, error.code, response.status);
}

const data = await response.json();
```

### 2. Implement Retry Logic

```javascript
async function fetchWithRetry(url, options, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch(url, options);

      if (response.status === 429) {
        const retryAfter = response.headers.get('X-RateLimit-Retry-After');
        await sleep(retryAfter * 1000);
        continue;
      }

      if (response.status >= 500) {
        await sleep(Math.pow(2, i) * 1000);
        continue;
      }

      return response;
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await sleep(Math.pow(2, i) * 1000);
    }
  }
}
```

### 3. Log Errors with Request IDs

```javascript
try {
  const data = await apiCall();
} catch (error) {
  console.error('API Error:', {
    message: error.message,
    code: error.code,
    requestId: error.requestId,
    timestamp: new Date().toISOString(),
  });
}
```

### 4. Provide User-Friendly Messages

```javascript
function getUserMessage(error) {
  switch (error.code) {
    case 'RATE_LIMIT_EXCEEDED':
      return 'Too many requests. Please try again in a few minutes.';
    case 'VALIDATION_ERROR':
      return 'Please check your input and try again.';
    case 'BUSINESS_NOT_FOUND':
      return 'Business not found. Please verify the ID.';
    default:
      return 'An error occurred. Please try again later.';
  }
}
```

***

## Error Codes Reference

| Code                  | Description                   | Action                   |
| --------------------- | ----------------------------- | ------------------------ |
| `INVALID_API_KEY`     | API key is invalid or missing | Check API key            |
| `RATE_LIMIT_EXCEEDED` | Too many requests             | Wait and retry           |
| `VALIDATION_ERROR`    | Invalid request parameters    | Fix parameters           |
| `BUSINESS_NOT_FOUND`  | Business doesn't exist        | Verify ID                |
| `UNAUTHORIZED`        | Insufficient permissions      | Check permissions        |
| `INTERNAL_ERROR`      | Server error                  | Retry or contact support |

***

## Need Help?

* 📧 Email: <support@aidp.dev>
* 📚 Documentation: [docs.aidp.dev/errors](https://docs.aidp.dev/errors)
