> ## Documentation Index
> Fetch the complete documentation index at: https://docs.getsnippets.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Error Codes

> Complete reference for API error codes and how to handle them

## Error Response Format

All errors follow a consistent JSON format:

```json theme={null}
{
	"success": false,
	"message": "Human-readable error description",
	"error": "Additional error details (optional)"
}
```

Some errors include additional context in the response:

```json theme={null}
{
	"success": false,
	"message": "Insufficient API requests",
	"usage": {
		"remainingRequests": 0,
		"requiredRequests": 5
	}
}
```

## HTTP Status Codes

### 2xx Success

<ResponseField name="200 OK" type="success">
  The request was successful. Response includes the requested data.

  ```json theme={null}
  {
    "success": true,
    "data": { /* requested data */ },
    "usage": {
      "remainingRequests": 99950
    }
  }
  ```
</ResponseField>

### 4xx Client Errors

<ResponseField name="400 Bad Request" type="error">
  **The request was malformed or contains invalid parameters.**

  Common causes:

  * Missing required parameters
  * Invalid JSON in request body
  * Invalid parameter values
  * Invalid data types
  * Field length violations

  ```json theme={null}
  {
    "success": false,
    "message": "Snippet ID is required"
  }
  ```

  **How to fix:**

  * Check that all required parameters are included
  * Validate JSON syntax
  * Verify parameter values match the expected format
  * Review field length requirements in the API docs
</ResponseField>

<ResponseField name="401 Unauthorized" type="error">
  **Authentication failed or API key is invalid.**

  Common causes:

  * Missing Authorization header
  * Invalid API key format
  * Inactive or deleted API key
  * Expired API key

  ```json theme={null}
  {
    "success": false,
    "message": "Invalid or inactive API key"
  }
  ```

  **How to fix:**

  * Verify the Authorization header is included: `Authorization: Bearer YOUR_KEY`
  * Check that the API key is correct
  * Confirm the API key is active in your dashboard
  * Create a new API key if necessary
</ResponseField>

<ResponseField name="403 Forbidden" type="error">
  **The API key doesn't have permission to access the resource.**

  Common causes:

  * API key lacks team permissions
  * Workspace subscription is inactive
  * Insufficient API request quota
  * Attempting to access another workspace's resources

  ```json theme={null}
  {
    "success": false,
    "message": "API key does not have access to this team"
  }
  ```

  **Insufficient quota example:**

  ```json theme={null}
  {
    "success": false,
    "message": "Insufficient API requests. This operation requires 5 requests but you have 0 remaining.",
    "usage": {
      "remainingRequests": 0,
      "requiredRequests": 5
    }
  }
  ```

  **How to fix:**

  * Update API key permissions to include the required teams
  * Check your workspace subscription status
  * Purchase additional API requests if quota is exhausted
  * Verify you're accessing resources in your workspace
</ResponseField>

<ResponseField name="404 Not Found" type="error">
  **The requested resource doesn't exist.**

  Common causes:

  * Invalid resource ID
  * Resource was deleted
  * Typo in the endpoint URL
  * Resource belongs to a different workspace

  ```json theme={null}
  {
    "success": false,
    "message": "Snippet not found"
  }
  ```

  **How to fix:**

  * Verify the resource ID is correct
  * Check if the resource was deleted
  * Confirm the endpoint URL is correct
  * Ensure the resource exists in your workspace
</ResponseField>

<ResponseField name="429 Too Many Requests" type="error">
  **Rate limit exceeded (20 requests per minute).**

  The response includes a `Retry-After` header indicating how long to wait before retrying.

  ```json theme={null}
  {
    "success": false,
    "message": "Rate limit exceeded. Too many requests from this API key. Try again in 120 seconds."
  }
  ```

  **Response headers:**

  ```
  Retry-After: 120
  ```

  **How to fix:**

  * Implement exponential backoff
  * Respect the `Retry-After` header
  * Use request queuing
  * Leverage batch endpoints to reduce request count
  * See [Rate Limiting](/api-reference/rate-limiting) for detailed strategies
</ResponseField>

### 5xx Server Errors

<ResponseField name="500 Internal Server Error" type="error">
  **An unexpected error occurred on the server.**

  ```json theme={null}
  {
    "success": false,
    "message": "Internal server error",
    "error": "Failed to process request"
  }
  ```

  **How to fix:**

  * Retry the request after a short delay
  * Contact support if the problem continues
</ResponseField>

## Common Error Scenarios

### Authentication Errors

<CodeGroup>
  ```json Missing Authorization Header theme={null}
  {
  	"success": false,
  	"message": "Authorization header with Bearer token is required"
  }
  ```

  ```json Invalid API Key Format theme={null}
  {
  	"success": false,
  	"message": "API key cannot be empty"
  }
  ```

  ```json Inactive API Key theme={null}
  {
  	"success": false,
  	"message": "Invalid or inactive API key"
  }
  ```
</CodeGroup>

### Validation Errors

<CodeGroup>
  ```json Missing Required Field theme={null}
  {
  	"success": false,
  	"message": "Title is required"
  }
  ```

  ```json Field Length Violation theme={null}
  {
  	"success": false,
  	"message": "Title cannot exceed 200 characters"
  }
  ```

  ```json Invalid Data Type theme={null}
  {
  	"success": false,
  	"message": "Content must be a valid object"
  }
  ```

  ```json Invalid JSON theme={null}
  {
  	"success": false,
  	"message": "Invalid JSON in request body"
  }
  ```
</CodeGroup>

### Permission Errors

<CodeGroup>
  ```json No Team Access theme={null}
  {
  	"success": false,
  	"message": "API key does not have access to this team"
  }
  ```

  ```json Wrong Workspace theme={null}
  {
  	"success": false,
  	"message": "API key does not have access to this workspace"
  }
  ```

  ```json Inactive Subscription theme={null}
  {
  	"success": false,
  	"message": "Workspace subscription is not active"
  }
  ```
</CodeGroup>

### Resource Errors

<CodeGroup>
  ```json Resource Not Found theme={null}
  {
  	"success": false,
  	"message": "Snippet not found"
  }
  ```

  ```json Folder Not Found theme={null}
  {
  	"success": false,
  	"message": "Folder not found or does not belong to the specified workspace/team"
  }
  ```

  ```json Tag Not Found theme={null}
  {
  	"success": false,
  	"message": "Tags not found: tag_uuid_1, tag_uuid_2"
  }
  ```
</CodeGroup>

### Quota Errors

<CodeGroup>
  ```json Insufficient Requests theme={null}
  {
  	"success": false,
  	"message": "Insufficient API requests. This operation requires 10 requests but you only have 5 remaining.",
  	"usage": {
  		"remainingRequests": 5,
  		"requiredRequests": 10
  	}
  }
  ```

  ```json No Requests Remaining theme={null}
  {
  	"success": false,
  	"message": "No API requests remaining",
  	"usage": {
  		"remainingRequests": 0
  	}
  }
  ```
</CodeGroup>

### Variation Errors

<CodeGroup>
  ```json Cannot Delete Last Variation theme={null}
  {
  	"success": false,
  	"message": "Cannot delete variations. The following snippets would have no variations left: My Snippet. Snippets must have at least one variation.",
  	"affectedSnippets": [
  		{
  			"snippetId": "snippet_uuid",
  			"title": "My Snippet"
  		}
  	]
  }
  ```

  ```json Variation Not Found theme={null}
  {
  	"success": false,
  	"message": "Variations not found: variation_uuid_1, variation_uuid_2"
  }
  ```
</CodeGroup>

### Batch Operation Errors

<CodeGroup>
  ```json Partial Success theme={null}
  {
  	"success": true,
  	"data": {
  		"message": "Some snippets created successfully",
  		"createdSnippets": [
  			/* ... */
  		]
  	},
  	"usage": {
  		"remainingRequests": 99900,
  		"usageDeducted": 100
  	},
  	"metadata": {
  		"requestedCount": 100,
  		"createdCount": 95,
  		"failedCount": 5,
  		"isPartialSuccess": true,
  		"failures": [
  			{
  				"originalIndex": 10,
  				"title": "Failed Snippet",
  				"error": "Folder not found"
  			}
  		]
  	}
  }
  ```

  ```json Complete Failure theme={null}
  {
  	"success": false,
  	"message": "Failed to create any snippets",
  	"usage": {
  		"remainingRequests": 99900,
  		"usageDeducted": 100
  	},
  	"failures": [
  		/* ... */
  	]
  }
  ```
</CodeGroup>

## Error Handling Best Practices

### Retry Strategy

Implement intelligent retry logic with exponential backoff:

```javascript theme={null}
async function apiCallWithRetry(apiCall, maxRetries = 3) {
	for (let attempt = 0; attempt < maxRetries; attempt++) {
		try {
			return await apiCall();
		} catch (error) {
			const status = error.response?.status;

			// Don't retry client errors (except 429)
			if (status >= 400 && status < 500 && status !== 429) {
				throw error;
			}

			// For 429 or 5xx, wait and retry
			if (attempt < maxRetries - 1) {
				const baseDelay =
					status === 429
						? parseInt(error.response?.headers['retry-after'] || 60) * 1000
						: 1000;

				const delay = baseDelay * Math.pow(2, attempt);
				await new Promise((resolve) => setTimeout(resolve, delay));
			} else {
				throw error;
			}
		}
	}
}
```

### Comprehensive Error Handler

```javascript theme={null}
function handleAPIError(error) {
	if (!error.response) {
		// Network error
		console.error('Network error:', error.message);
		return {
			type: 'network',
			message: 'Unable to connect to the API',
			retryable: true,
		};
	}

	const { status, data } = error.response;

	switch (status) {
		case 400:
			return {
				type: 'validation',
				message: data.message || 'Invalid request',
				retryable: false,
			};

		case 401:
			return {
				type: 'authentication',
				message: 'Invalid API key',
				retryable: false,
				action: 'CHECK_API_KEY',
			};

		case 403:
			if (data.message?.includes('API requests')) {
				return {
					type: 'quota',
					message: 'API quota exceeded',
					retryable: false,
					action: 'UPGRADE_PLAN',
				};
			}
			return {
				type: 'permission',
				message: data.message || 'Insufficient permissions',
				retryable: false,
				action: 'UPDATE_PERMISSIONS',
			};

		case 404:
			return {
				type: 'not_found',
				message: data.message || 'Resource not found',
				retryable: false,
			};

		case 429:
			return {
				type: 'rate_limit',
				message: 'Rate limit exceeded',
				retryable: true,
				retryAfter: error.response.headers['retry-after'],
			};

		case 500:
		default:
			return {
				type: 'server',
				message: 'Server error occurred',
				retryable: true,
			};
	}
}

// Usage
try {
	const result = await apiCall();
} catch (error) {
	const errorInfo = handleAPIError(error);

	if (errorInfo.retryable) {
		// Retry logic
	} else {
		// Show user-friendly error message
		console.error(errorInfo.message);
	}
}
```

### User-Friendly Messages

Map technical errors to user-friendly messages:

```javascript theme={null}
const ERROR_MESSAGES = {
	'Invalid or inactive API key':
		'There was an authentication problem. Please contact support.',
	'API key does not have access to this team':
		"You don't have permission to access this resource.",
	'Insufficient API requests':
		'API usage limit reached. Please upgrade your plan.',
	'Rate limit exceeded':
		'Too many requests. Please wait a moment and try again.',
	'Snippet not found':
		"The snippet you're looking for doesn't exist or was deleted.",
	default: 'Something went wrong. Please try again or contact support.',
};

function getUserFriendlyMessage(apiError) {
	return ERROR_MESSAGES[apiError.message] || ERROR_MESSAGES.default;
}
```

## Logging and Monitoring

Track errors to identify patterns and issues:

```javascript theme={null}
class APILogger {
	logError(error, context) {
		const logEntry = {
			timestamp: new Date().toISOString(),
			status: error.response?.status,
			message: error.response?.data?.message,
			endpoint: context.endpoint,
			method: context.method,
			requestId: error.response?.headers['x-request-id'],
			// Don't log API keys!
			user: context.userId,
		};

		// Send to your logging service
		console.error('API Error:', logEntry);

		// Alert on critical errors
		if (error.response?.status >= 500) {
			this.alertTeam(logEntry);
		}
	}

	alertTeam(logEntry) {
		// Send to Slack, PagerDuty, etc.
	}
}
```

## Need Help?

If you're experiencing persistent errors:

<CardGroup cols={2}>
  <Card title="Support" icon="life-ring" href="mailto:team@getsnippets.ai">
    Contact our support team
  </Card>

  <Card title="Documentation" icon="book" href="/api-reference/introduction">
    Review the full API documentation
  </Card>
</CardGroup>
