# Tara API Error Handling

Comprehensive guide to error responses, error codes, and troubleshooting in the
Tara API.

## Error Response Format

All error responses follow a consistent format:

```json
{
  "success": false,
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable error description",
    "details": [
      {
        "field": "fieldName",
        "message": "Field-specific error message",
        "code": "FIELD_ERROR_CODE"
      }
    ],
    "hint": "Optional suggestion for resolving the error",
    "documentationUrl": "https://docs.tara.app/errors/ERROR_CODE"
  },
  "meta": {
    "requestId": "550e8400-e29b-41d4-a716-446655440000",
    "timestamp": "2024-01-15T10:30:00.000Z"
  }
}
```

### Response Fields

| Field                    | Type    | Description                           |
| ------------------------ | ------- | ------------------------------------- |
| `success`                | boolean | Always `false` for errors             |
| `error.code`             | string  | Machine-readable error code           |
| `error.message`          | string  | Human-readable error description      |
| `error.details`          | array   | Field-specific errors (validation)    |
| `error.hint`             | string  | Suggestion for resolving the error    |
| `error.documentationUrl` | string  | Link to error documentation           |
| `meta.requestId`         | string  | Unique request identifier for support |
| `meta.timestamp`         | string  | ISO 8601 timestamp                    |

## HTTP Status Codes

| Status | Meaning               | Description                               |
| ------ | --------------------- | ----------------------------------------- |
| 400    | Bad Request           | Invalid request syntax or parameters      |
| 401    | Unauthorized          | Missing or invalid authentication         |
| 403    | Forbidden             | Authenticated but not authorized          |
| 404    | Not Found             | Resource does not exist                   |
| 409    | Conflict              | Resource already exists or state conflict |
| 422    | Unprocessable Entity  | Validation error                          |
| 429    | Too Many Requests     | Rate limit exceeded                       |
| 500    | Internal Server Error | Server-side error                         |
| 502    | Bad Gateway           | Upstream service error                    |
| 503    | Service Unavailable   | Service temporarily unavailable           |
| 504    | Gateway Timeout       | Upstream service timeout                  |

## Error Code Reference

### Authentication Errors (AUTH\_\*)

| Code                            | HTTP | Description                         | Resolution                                     |
| ------------------------------- | ---- | ----------------------------------- | ---------------------------------------------- |
| `AUTH_REQUIRED`                 | 401  | No authentication token provided    | Include `Authorization: Bearer <token>` header |
| `AUTH_INVALID_TOKEN`            | 401  | Token is malformed or corrupted     | Obtain a new token via login                   |
| `AUTH_TOKEN_EXPIRED`            | 401  | Access token has expired            | Refresh using refresh token                    |
| `AUTH_REFRESH_INVALID`          | 401  | Refresh token is invalid or revoked | Re-authenticate                                |
| `AUTH_REFRESH_EXPIRED`          | 401  | Refresh token has expired           | Re-authenticate                                |
| `AUTH_REFRESH_REUSED`           | 401  | Refresh token reuse detected        | Re-authenticate (security event)               |
| `AUTH_INVALID_CREDENTIALS`      | 401  | Email or password incorrect         | Check credentials                              |
| `AUTH_ACCOUNT_DISABLED`         | 403  | Account has been disabled           | Contact support                                |
| `AUTH_EMAIL_NOT_VERIFIED`       | 403  | Email verification required         | Verify email first                             |
| `AUTH_INSUFFICIENT_PERMISSIONS` | 403  | User lacks required permissions     | Upgrade subscription or contact support        |

**Example - Token Expired:**

```json
{
  "success": false,
  "error": {
    "code": "AUTH_TOKEN_EXPIRED",
    "message": "Your access token has expired",
    "hint": "Use the /auth/refresh endpoint with your refresh token to obtain a new access token"
  }
}
```

### Validation Errors (VALIDATION\_\*)

| Code                  | HTTP | Description                          |
| --------------------- | ---- | ------------------------------------ |
| `VALIDATION_ERROR`    | 422  | One or more fields failed validation |
| `VALIDATION_REQUIRED` | 422  | Required field is missing            |
| `VALIDATION_TYPE`     | 422  | Field has wrong type                 |
| `VALIDATION_FORMAT`   | 422  | Field format is invalid              |
| `VALIDATION_RANGE`    | 422  | Value outside allowed range          |
| `VALIDATION_LENGTH`   | 422  | String length out of bounds          |
| `VALIDATION_PATTERN`  | 422  | Value doesn't match pattern          |
| `VALIDATION_ENUM`     | 422  | Value not in allowed set             |

**Example - Validation Error:**

```json
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request validation failed",
    "details": [
      {
        "field": "email",
        "message": "Invalid email format",
        "code": "VALIDATION_FORMAT"
      },
      {
        "field": "password",
        "message": "Password must be at least 8 characters",
        "code": "VALIDATION_LENGTH"
      }
    ]
  }
}
```

### Resource Errors (RESOURCE\_\*)

| Code                      | HTTP | Description                      |
| ------------------------- | ---- | -------------------------------- |
| `RESOURCE_NOT_FOUND`      | 404  | Requested resource doesn't exist |
| `RESOURCE_ALREADY_EXISTS` | 409  | Resource with identifier exists  |
| `RESOURCE_CONFLICT`       | 409  | Resource state conflict          |
| `RESOURCE_DELETED`        | 410  | Resource was deleted             |
| `RESOURCE_LOCKED`         | 423  | Resource is locked               |

**Example - Not Found:**

```json
{
  "success": false,
  "error": {
    "code": "RESOURCE_NOT_FOUND",
    "message": "Meditation not found",
    "details": [
      {
        "field": "meditationId",
        "message": "No meditation exists with ID 'med_invalid'"
      }
    ]
  }
}
```

### User Errors (USER\_\*)

| Code                        | HTTP | Description                         |
| --------------------------- | ---- | ----------------------------------- |
| `USER_NOT_FOUND`            | 404  | User does not exist                 |
| `USER_ALREADY_EXISTS`       | 409  | Email already registered            |
| `USER_INVALID_PASSWORD`     | 400  | Password doesn't meet requirements  |
| `USER_PASSWORD_MISMATCH`    | 400  | Password confirmation doesn't match |
| `USER_RESET_TOKEN_INVALID`  | 400  | Password reset token invalid        |
| `USER_RESET_TOKEN_EXPIRED`  | 400  | Password reset token expired        |
| `USER_VERIFICATION_INVALID` | 400  | Email verification token invalid    |

**Example - Email Already Exists:**

```json
{
  "success": false,
  "error": {
    "code": "USER_ALREADY_EXISTS",
    "message": "An account with this email already exists",
    "hint": "Try logging in or use forgot password to recover your account"
  }
}
```

### Subscription Errors (SUBSCRIPTION\_\*)

| Code                           | HTTP | Description                   |
| ------------------------------ | ---- | ----------------------------- |
| `SUBSCRIPTION_REQUIRED`        | 403  | Premium subscription required |
| `SUBSCRIPTION_EXPIRED`         | 403  | Subscription has expired      |
| `SUBSCRIPTION_INVALID_RECEIPT` | 400  | Receipt validation failed     |
| `SUBSCRIPTION_ALREADY_ACTIVE`  | 409  | Subscription already active   |
| `SUBSCRIPTION_RESTORE_FAILED`  | 400  | Could not restore purchases   |

**Example - Premium Required:**

```json
{
  "success": false,
  "error": {
    "code": "SUBSCRIPTION_REQUIRED",
    "message": "This meditation requires a premium subscription",
    "hint": "Upgrade to Tara Premium to access all meditations"
  }
}
```

### Session Errors (SESSION\_\*)

| Code                        | HTTP | Description                     |
| --------------------------- | ---- | ------------------------------- |
| `SESSION_NOT_FOUND`         | 404  | Session does not exist          |
| `SESSION_ALREADY_COMPLETED` | 409  | Session already marked complete |
| `SESSION_EXPIRED`           | 400  | Session has expired             |
| `SESSION_INVALID_STATE`     | 400  | Invalid state transition        |

### Rate Limiting Errors (RATE\_\*)

| Code                  | HTTP | Description                       |
| --------------------- | ---- | --------------------------------- |
| `RATE_LIMIT_EXCEEDED` | 429  | Too many requests                 |
| `RATE_LIMIT_AUTH`     | 429  | Auth endpoint rate limit exceeded |

**Example - Rate Limited:**

```json
{
  "success": false,
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Too many requests",
    "details": [
      {
        "field": "retryAfter",
        "message": "60"
      }
    ],
    "hint": "Wait 60 seconds before making another request"
  }
}
```

**Rate Limit Headers:**

```http
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1705316700
Retry-After: 60
```

### Server Errors (SERVER\_\*)

| Code                 | HTTP | Description                     |
| -------------------- | ---- | ------------------------------- |
| `SERVER_ERROR`       | 500  | Unexpected server error         |
| `SERVER_UNAVAILABLE` | 503  | Service temporarily unavailable |
| `SERVER_TIMEOUT`     | 504  | Request timed out               |
| `SERVER_MAINTENANCE` | 503  | Server under maintenance        |

**Example - Server Error:**

```json
{
  "success": false,
  "error": {
    "code": "SERVER_ERROR",
    "message": "An unexpected error occurred",
    "hint": "Please try again. If the problem persists, contact support with request ID."
  },
  "meta": {
    "requestId": "550e8400-e29b-41d4-a716-446655440000"
  }
}
```

### External Service Errors (EXTERNAL\_\*)

| Code                       | HTTP | Description                        |
| -------------------------- | ---- | ---------------------------------- |
| `EXTERNAL_SERVICE_ERROR`   | 502  | External service returned an error |
| `EXTERNAL_SERVICE_TIMEOUT` | 504  | External service timed out         |
| `EXTERNAL_OAUTH_ERROR`     | 400  | OAuth provider returned an error   |
| `EXTERNAL_PAYMENT_ERROR`   | 400  | Payment processor error            |

## Client Error Handling

### TypeScript/JavaScript

```typescript
import { TaraClient, TaraError, ErrorCode } from '@tara/sdk';

const client = new TaraClient({ baseUrl: 'https://api.tara.app' });

async function getMeditation(id: string) {
  try {
    const meditation = await client.meditations.get(id);
    return meditation;
  } catch (error) {
    if (error instanceof TaraError) {
      switch (error.code) {
        case ErrorCode.AUTH_TOKEN_EXPIRED:
          // Refresh token and retry
          await client.auth.refresh();
          return client.meditations.get(id);

        case ErrorCode.RESOURCE_NOT_FOUND:
          // Handle missing resource
          console.log('Meditation not found');
          return null;

        case ErrorCode.SUBSCRIPTION_REQUIRED:
          // Prompt user to upgrade
          navigation.navigate('Subscription');
          return null;

        case ErrorCode.RATE_LIMIT_EXCEEDED:
          // Wait and retry
          const retryAfter = error.details?.find(
            (d) => d.field === 'retryAfter'
          )?.message;
          await sleep(parseInt(retryAfter || '60') * 1000);
          return client.meditations.get(id);

        default:
          // Log and show generic error
          console.error('API Error:', error.code, error.message);
          showToast('Something went wrong. Please try again.');
          return null;
      }
    }
    throw error;
  }
}
```

### React Native Error Boundary

```typescript
import { ErrorBoundary } from 'react-error-boundary';
import { TaraError, ErrorCode } from '@tara/sdk';

function ErrorFallback({ error, resetErrorBoundary }) {
  if (error instanceof TaraError) {
    if (error.code === ErrorCode.AUTH_TOKEN_EXPIRED) {
      // Auto-redirect to login
      return <LoginScreen onSuccess={resetErrorBoundary} />;
    }

    if (error.code === ErrorCode.SUBSCRIPTION_REQUIRED) {
      return <SubscriptionPrompt onDismiss={resetErrorBoundary} />;
    }
  }

  return (
    <View style={styles.error}>
      <Text>Something went wrong</Text>
      <Text>{error.message}</Text>
      <Button onPress={resetErrorBoundary} title="Try Again" />
    </View>
  );
}

function App() {
  return (
    <ErrorBoundary FallbackComponent={ErrorFallback}>
      <MainApp />
    </ErrorBoundary>
  );
}
```

### Retry Logic with Exponential Backoff

```typescript
async function withRetry<T>(
  fn: () => Promise<T>,
  options: {
    maxRetries?: number;
    baseDelay?: number;
    maxDelay?: number;
    retryOn?: string[];
  } = {}
): Promise<T> {
  const {
    maxRetries = 3,
    baseDelay = 1000,
    maxDelay = 30000,
    retryOn = ['SERVER_ERROR', 'SERVER_TIMEOUT', 'RATE_LIMIT_EXCEEDED'],
  } = options;

  let lastError: Error;

  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      lastError = error;

      if (error instanceof TaraError) {
        // Don't retry client errors (except rate limits)
        if (!retryOn.includes(error.code)) {
          throw error;
        }

        // Use Retry-After header if available
        if (error.code === 'RATE_LIMIT_EXCEEDED') {
          const retryAfter = error.details?.find(
            (d) => d.field === 'retryAfter'
          )?.message;
          if (retryAfter) {
            await sleep(parseInt(retryAfter) * 1000);
            continue;
          }
        }
      }

      if (attempt < maxRetries) {
        // Exponential backoff with jitter
        const delay = Math.min(
          baseDelay * Math.pow(2, attempt) + Math.random() * 1000,
          maxDelay
        );
        await sleep(delay);
      }
    }
  }

  throw lastError;
}

// Usage
const meditation = await withRetry(() => client.meditations.get(id));
```

## Debugging Errors

### Using Request ID

Every response includes a `requestId` in the `meta` object. Use this ID when:

1. Contacting support
2. Searching logs
3. Correlating client and server events

```typescript
try {
  await client.meditations.get(id);
} catch (error) {
  if (error instanceof TaraError) {
    // Log request ID for debugging
    console.error('Request failed:', {
      requestId: error.meta?.requestId,
      code: error.code,
      message: error.message,
    });

    // Report to crash analytics
    crashlytics().recordError(error, {
      requestId: error.meta?.requestId,
      errorCode: error.code,
    });
  }
}
```

### Common Issues and Solutions

#### "AUTH_TOKEN_EXPIRED" happening frequently

**Cause:** Access tokens expire after 15 minutes by default.

**Solutions:**

1. Implement automatic token refresh in your HTTP client
2. Refresh tokens proactively before expiration
3. Check that device clock is synchronized

```typescript
// Proactive token refresh
const tokenExpiresAt = decodeJwt(accessToken).exp * 1000;
const refreshThreshold = 60000; // 1 minute before expiry

if (Date.now() > tokenExpiresAt - refreshThreshold) {
  await client.auth.refresh();
}
```

#### "VALIDATION_ERROR" on registration

**Common causes:**

- Password too weak
- Invalid email format
- Missing required fields

**Check password requirements:**

- Minimum 8 characters
- At least one uppercase letter
- At least one lowercase letter
- At least one number
- At least one special character

#### "SUBSCRIPTION_REQUIRED" for free content

**Cause:** Content may have been reclassified, or subscription status not
synced.

**Solutions:**

1. Verify receipt to sync subscription status
2. Restore purchases
3. Clear local subscription cache

```typescript
// Sync subscription status
await client.subscriptions.verify({
  receipt: currentReceipt,
  platform: 'ios',
});
```

#### "RATE_LIMIT_EXCEEDED" in normal usage

**Cause:** Making too many requests in a short period.

**Solutions:**

1. Implement request batching
2. Add local caching
3. Use pagination efficiently

```typescript
// Bad: Making individual requests
for (const id of meditationIds) {
  await client.meditations.get(id); // Rate limited!
}

// Good: Batch fetch
const meditations = await client.meditations.list({
  ids: meditationIds,
});
```

## Error Monitoring

### Recommended Tools

- **Sentry**: Full-stack error tracking
- **Crashlytics**: Mobile crash reporting
- **LogRocket**: Session replay with errors
- **Datadog**: APM and error tracking

### Sentry Integration

```typescript
import * as Sentry from '@sentry/react-native';
import { TaraError } from '@tara/sdk';

Sentry.init({
  dsn: 'your-sentry-dsn',
  beforeSend(event, hint) {
    const error = hint.originalException;

    if (error instanceof TaraError) {
      // Add Tara-specific context
      event.tags = {
        ...event.tags,
        'tara.error_code': error.code,
        'tara.request_id': error.meta?.requestId,
      };

      // Don't report expected errors
      const ignoredCodes = [
        'AUTH_TOKEN_EXPIRED',
        'VALIDATION_ERROR',
        'RESOURCE_NOT_FOUND',
      ];

      if (ignoredCodes.includes(error.code)) {
        return null;
      }
    }

    return event;
  },
});
```

## Support

If you encounter persistent errors:

1. **Check API Status**: https://status.tara.app
2. **Search Documentation**: https://docs.tara.app/errors
3. **Developer Discord**: https://discord.gg/tara-dev
4. **Email Support**: api-support@tara.app (include request ID)

When contacting support, always include:

- Request ID from error response
- Timestamp of the error
- Endpoint and HTTP method
- Request body (sanitized)
- Client version and platform
