# Yemaya API Error Reference

This document provides a comprehensive reference for all error codes and responses returned by the Yemaya API. The API uses [RFC 7807 Problem Details](https://tools.ietf.org/html/rfc7807) for error responses.

## Table of Contents

- [Error Response Format](#error-response-format)
- [Client Errors (4xx)](#client-errors-4xx)
- [Server Errors (5xx)](#server-errors-5xx)
- [Custom Error Codes](#custom-error-codes)
- [Validation Errors](#validation-errors)
- [Error Handling Best Practices](#error-handling-best-practices)

---

## Error Response Format

All API errors follow the RFC 7807 Problem Details format:

```json
{
  "type": "https://api.yemaya.io/problems/validation-error",
  "title": "Validation Error",
  "status": 400,
  "detail": "Request validation failed",
  "instance": "/v1/projects",
  "requestId": "req_abc123xyz",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "errors": [
    {
      "field": "email",
      "message": "Invalid email format",
      "code": "invalid_email"
    }
  ]
}
```

### Response Fields

| Field | Type | Description |
|-------|------|-------------|
| `type` | string | URI reference identifying the problem type |
| `title` | string | Short, human-readable summary of the problem |
| `status` | number | HTTP status code |
| `detail` | string | Human-readable explanation specific to this occurrence |
| `instance` | string | URI reference to the specific occurrence (request path) |
| `requestId` | string | Unique request identifier for support |
| `timestamp` | string | ISO 8601 timestamp of the error |
| `errors` | array | Validation errors (for validation failures) |
| `extensions` | object | Additional context-specific data |

---

## Client Errors (4xx)

### 400 Bad Request

**Type:** `https://api.yemaya.io/problems/bad-request`

The request could not be understood by the server due to malformed syntax.

```json
{
  "type": "https://api.yemaya.io/problems/bad-request",
  "title": "Bad Request",
  "status": 400,
  "detail": "The request body could not be parsed as JSON"
}
```

**Common Causes:**
- Malformed JSON in request body
- Invalid query parameters
- Missing required headers
- Invalid content encoding

---

### 400 Validation Error

**Type:** `https://api.yemaya.io/problems/validation-error`

The request body failed schema validation.

```json
{
  "type": "https://api.yemaya.io/problems/validation-error",
  "title": "Validation Error",
  "status": 400,
  "detail": "Request validation failed",
  "errors": [
    {
      "field": "email",
      "message": "Invalid email format",
      "code": "invalid_string"
    },
    {
      "field": "password",
      "message": "Password must be at least 8 characters",
      "code": "too_small"
    }
  ]
}
```

**Common Validation Codes:**
| Code | Description |
|------|-------------|
| `invalid_type` | Wrong data type provided |
| `invalid_string` | String format validation failed |
| `invalid_enum` | Value not in allowed enum list |
| `too_small` | Value below minimum length/size |
| `too_big` | Value above maximum length/size |
| `invalid_date` | Invalid date format |
| `required` | Required field is missing |

---

### 401 Unauthorized

**Type:** `https://api.yemaya.io/problems/unauthorized`

Authentication is required or has failed.

```json
{
  "type": "https://api.yemaya.io/problems/unauthorized",
  "title": "Unauthorized",
  "status": 401,
  "detail": "Invalid or expired access token"
}
```

**Common Causes:**
- Missing Authorization header
- Invalid or expired JWT token
- Invalid API key
- Token has been revoked

**Headers Returned:**
```
WWW-Authenticate: Bearer realm="api.yemaya.io"
```

---

### 403 Forbidden

**Type:** `https://api.yemaya.io/problems/forbidden`

The authenticated user does not have permission to access the resource.

```json
{
  "type": "https://api.yemaya.io/problems/forbidden",
  "title": "Forbidden",
  "status": 403,
  "detail": "You do not have permission to access this project",
  "extensions": {
    "requiredRole": "editor",
    "currentRole": "viewer"
  }
}
```

**Common Causes:**
- Insufficient role permissions
- Resource belongs to another user
- Organization-level restrictions
- Feature not available on current plan

---

### 404 Not Found

**Type:** `https://api.yemaya.io/problems/not-found`

The requested resource could not be found.

```json
{
  "type": "https://api.yemaya.io/problems/not-found",
  "title": "Not Found",
  "status": 404,
  "detail": "Project with ID 'prj_abc123' was not found",
  "extensions": {
    "resourceType": "project",
    "resourceId": "prj_abc123"
  }
}
```

**Common Causes:**
- Resource does not exist
- Resource has been deleted
- Incorrect resource ID format
- Resource belongs to a different organization

---

### 405 Method Not Allowed

**Type:** `https://api.yemaya.io/problems/method-not-allowed`

The HTTP method is not allowed for this endpoint.

```json
{
  "type": "https://api.yemaya.io/problems/method-not-allowed",
  "title": "Method Not Allowed",
  "status": 405,
  "detail": "POST method is not allowed on this endpoint",
  "extensions": {
    "allowedMethods": ["GET", "PATCH", "DELETE"]
  }
}
```

**Headers Returned:**
```
Allow: GET, PATCH, DELETE
```

---

### 409 Conflict

**Type:** `https://api.yemaya.io/problems/conflict`

The request conflicts with the current state of the resource.

```json
{
  "type": "https://api.yemaya.io/problems/conflict",
  "title": "Conflict",
  "status": 409,
  "detail": "A user with this email already exists",
  "extensions": {
    "conflictingField": "email"
  }
}
```

**Common Causes:**
- Duplicate unique field (email, username)
- Concurrent modification conflict
- Resource state prevents operation
- Version mismatch (optimistic locking)

---

### 410 Gone

**Type:** `https://api.yemaya.io/problems/gone`

The resource is no longer available and will not be available again.

```json
{
  "type": "https://api.yemaya.io/problems/gone",
  "title": "Gone",
  "status": 410,
  "detail": "This resource has been permanently deleted"
}
```

**Common Causes:**
- Resource was permanently deleted
- API endpoint has been deprecated and removed

---

### 413 Payload Too Large

**Type:** `https://api.yemaya.io/problems/payload-too-large`

The request entity is larger than the server will process.

```json
{
  "type": "https://api.yemaya.io/problems/payload-too-large",
  "title": "Payload Too Large",
  "status": 413,
  "detail": "Request body exceeds maximum size of 10MB",
  "extensions": {
    "maxSize": 10485760,
    "receivedSize": 15728640
  }
}
```

**Limits:**
| Endpoint | Maximum Size |
|----------|-------------|
| General API | 10 MB |
| File uploads | 100 MB |
| Batch operations | 50 MB |

---

### 415 Unsupported Media Type

**Type:** `https://api.yemaya.io/problems/unsupported-media-type`

The request content type is not supported.

```json
{
  "type": "https://api.yemaya.io/problems/unsupported-media-type",
  "title": "Unsupported Media Type",
  "status": 415,
  "detail": "Content-Type 'text/plain' is not supported",
  "extensions": {
    "supportedTypes": ["application/json", "multipart/form-data"]
  }
}
```

---

### 422 Unprocessable Entity

**Type:** `https://api.yemaya.io/problems/unprocessable-entity`

The request was well-formed but could not be processed.

```json
{
  "type": "https://api.yemaya.io/problems/unprocessable-entity",
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Cannot delete a project with active collaborators"
}
```

**Common Causes:**
- Business logic validation failed
- Operation not allowed in current state
- Semantic errors in request

---

### 429 Rate Limited

**Type:** `https://api.yemaya.io/problems/rate-limited`

Too many requests have been made.

```json
{
  "type": "https://api.yemaya.io/problems/rate-limited",
  "title": "Too Many Requests",
  "status": 429,
  "detail": "Rate limit exceeded. Please retry after 60 seconds",
  "extensions": {
    "limit": 1000,
    "remaining": 0,
    "resetAt": "2024-01-15T10:31:00.000Z"
  }
}
```

**Headers Returned:**
```
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1705318260
Retry-After: 60
```

**Rate Limits:**
| Tier | Requests per Minute |
|------|---------------------|
| Free | 60 |
| Pro | 1000 |
| Enterprise | 10000 |

---

## Server Errors (5xx)

### 500 Internal Server Error

**Type:** `https://api.yemaya.io/problems/internal-error`

An unexpected error occurred on the server.

```json
{
  "type": "https://api.yemaya.io/problems/internal-error",
  "title": "Internal Server Error",
  "status": 500,
  "detail": "An unexpected error occurred",
  "requestId": "req_xyz789"
}
```

**What to Do:**
1. Note the `requestId` for support
2. Retry the request after a short delay
3. Contact support if the error persists

---

### 501 Not Implemented

**Type:** `https://api.yemaya.io/problems/not-implemented`

The server does not support the functionality required.

```json
{
  "type": "https://api.yemaya.io/problems/not-implemented",
  "title": "Not Implemented",
  "status": 501,
  "detail": "This feature is not yet implemented"
}
```

---

### 502 Bad Gateway

**Type:** `https://api.yemaya.io/problems/bad-gateway`

The server received an invalid response from an upstream server.

```json
{
  "type": "https://api.yemaya.io/problems/bad-gateway",
  "title": "Bad Gateway",
  "status": 502,
  "detail": "Error communicating with upstream service"
}
```

---

### 503 Service Unavailable

**Type:** `https://api.yemaya.io/problems/service-unavailable`

The server is temporarily unable to handle the request.

```json
{
  "type": "https://api.yemaya.io/problems/service-unavailable",
  "title": "Service Unavailable",
  "status": 503,
  "detail": "Service is temporarily unavailable for maintenance",
  "extensions": {
    "retryAfter": 300
  }
}
```

**Headers Returned:**
```
Retry-After: 300
```

---

### 504 Gateway Timeout

**Type:** `https://api.yemaya.io/problems/gateway-timeout`

The server did not receive a timely response from an upstream server.

```json
{
  "type": "https://api.yemaya.io/problems/gateway-timeout",
  "title": "Gateway Timeout",
  "status": 504,
  "detail": "Request timed out waiting for upstream service"
}
```

---

## Custom Error Codes

### Quota Exceeded

**Type:** `https://api.yemaya.io/problems/quota-exceeded`

A usage quota has been exceeded.

```json
{
  "type": "https://api.yemaya.io/problems/quota-exceeded",
  "title": "Quota Exceeded",
  "status": 402,
  "detail": "Monthly AI generation quota exceeded",
  "extensions": {
    "quotaType": "ai_generations",
    "limit": 1000,
    "used": 1000,
    "resetAt": "2024-02-01T00:00:00.000Z"
  }
}
```

---

### Resource Locked

**Type:** `https://api.yemaya.io/problems/resource-locked`

The resource is locked by another user or process.

```json
{
  "type": "https://api.yemaya.io/problems/resource-locked",
  "title": "Resource Locked",
  "status": 423,
  "detail": "This scene is currently being edited by another user",
  "extensions": {
    "lockedBy": "usr_xyz789",
    "lockedAt": "2024-01-15T10:20:00.000Z",
    "lockedUntil": "2024-01-15T10:35:00.000Z"
  }
}
```

---

### Feature Disabled

**Type:** `https://api.yemaya.io/problems/feature-disabled`

A feature is disabled for the current user or organization.

```json
{
  "type": "https://api.yemaya.io/problems/feature-disabled",
  "title": "Feature Disabled",
  "status": 403,
  "detail": "AI image generation is not available on your current plan",
  "extensions": {
    "feature": "ai_image_generation",
    "requiredPlan": "pro"
  }
}
```

---

### External Service Error

**Type:** `https://api.yemaya.io/problems/external-service-error`

An external service (AI provider, storage, etc.) returned an error.

```json
{
  "type": "https://api.yemaya.io/problems/external-service-error",
  "title": "External Service Error",
  "status": 502,
  "detail": "AI service temporarily unavailable",
  "extensions": {
    "service": "openai",
    "originalError": "rate_limit_exceeded"
  }
}
```

---

### Database Error

**Type:** `https://api.yemaya.io/problems/database-error`

A database operation failed.

```json
{
  "type": "https://api.yemaya.io/problems/database-error",
  "title": "Database Error",
  "status": 500,
  "detail": "A database error occurred. Please try again later.",
  "requestId": "req_abc123"
}
```

---

## Validation Errors

Validation errors include detailed information about which fields failed validation:

```json
{
  "type": "https://api.yemaya.io/problems/validation-error",
  "title": "Validation Error",
  "status": 400,
  "detail": "Request validation failed",
  "errors": [
    {
      "field": "name",
      "message": "Name is required",
      "code": "required"
    },
    {
      "field": "email",
      "message": "Must be a valid email address",
      "code": "invalid_string"
    },
    {
      "field": "age",
      "message": "Age must be at least 18",
      "code": "too_small"
    }
  ]
}
```

### Field Path Notation

For nested objects, the field path uses dot notation:

```json
{
  "errors": [
    {
      "field": "address.zipCode",
      "message": "Invalid zip code format",
      "code": "invalid_string"
    },
    {
      "field": "items[0].quantity",
      "message": "Quantity must be positive",
      "code": "too_small"
    }
  ]
}
```

---

## Error Handling Best Practices

### 1. Always Check the Status Code

```typescript
const response = await fetch('https://api.yemaya.io/v1/projects');

if (!response.ok) {
  const error = await response.json();
  throw new Error(`${error.title}: ${error.detail}`);
}
```

### 2. Handle Specific Error Types

```typescript
async function handleApiError(error: ProblemDetails) {
  switch (error.type) {
    case 'https://api.yemaya.io/problems/unauthorized':
      // Redirect to login
      await refreshToken();
      break;

    case 'https://api.yemaya.io/problems/rate-limited':
      // Wait and retry
      const retryAfter = error.extensions?.retryAfter || 60;
      await delay(retryAfter * 1000);
      break;

    case 'https://api.yemaya.io/problems/validation-error':
      // Show field errors
      displayFieldErrors(error.errors);
      break;

    default:
      // Show generic error
      showError(error.detail);
  }
}
```

### 3. Log Request IDs

Always log the `requestId` for debugging:

```typescript
console.error(`API Error [${error.requestId}]: ${error.detail}`);
```

### 4. Implement Retry Logic

```typescript
async function fetchWithRetry(url: string, options: RequestInit, retries = 3) {
  for (let attempt = 0; attempt < retries; attempt++) {
    const response = await fetch(url, options);

    if (response.ok) {
      return response;
    }

    if (response.status === 429) {
      const retryAfter = response.headers.get('Retry-After') || '60';
      await delay(parseInt(retryAfter) * 1000);
      continue;
    }

    if (response.status >= 500) {
      await delay(Math.pow(2, attempt) * 1000); // Exponential backoff
      continue;
    }

    // Client errors should not be retried
    throw new Error(await response.text());
  }

  throw new Error('Max retries exceeded');
}
```

### 5. Display User-Friendly Messages

```typescript
const userFriendlyMessages: Record<string, string> = {
  'https://api.yemaya.io/problems/unauthorized':
    'Your session has expired. Please log in again.',
  'https://api.yemaya.io/problems/rate-limited':
    'You\'re making requests too quickly. Please slow down.',
  'https://api.yemaya.io/problems/quota-exceeded':
    'You\'ve reached your usage limit for this month.',
  'https://api.yemaya.io/problems/service-unavailable':
    'We\'re experiencing technical difficulties. Please try again later.',
};

function getErrorMessage(error: ProblemDetails): string {
  return userFriendlyMessages[error.type] || error.detail;
}
```

---

## Quick Reference

| Status | Type | Description |
|--------|------|-------------|
| 400 | bad-request | Malformed request syntax |
| 400 | validation-error | Request validation failed |
| 401 | unauthorized | Authentication required or failed |
| 403 | forbidden | Insufficient permissions |
| 404 | not-found | Resource not found |
| 405 | method-not-allowed | HTTP method not allowed |
| 409 | conflict | Request conflicts with current state |
| 410 | gone | Resource permanently deleted |
| 413 | payload-too-large | Request body too large |
| 415 | unsupported-media-type | Content-Type not supported |
| 422 | unprocessable-entity | Semantic validation failed |
| 429 | rate-limited | Too many requests |
| 500 | internal-error | Unexpected server error |
| 501 | not-implemented | Feature not implemented |
| 502 | bad-gateway | Upstream server error |
| 503 | service-unavailable | Temporary unavailability |
| 504 | gateway-timeout | Upstream server timeout |

---

## Need Help?

If you encounter an error that you cannot resolve:

1. Check the `requestId` in the error response
2. Review your request parameters and authentication
3. Check our [status page](https://status.yemaya.io) for any ongoing issues
4. Contact support at api@yemaya.io with the `requestId`
