Overview
The MythIQ API uses standard HTTP status codes to indicate the success or failure of a request. In addition to the status code, error responses include a JSON body with detailed information about what went wrong and how to resolve the issue.
Understanding these errors and implementing proper error handling in your applications is essential for creating a robust and user-friendly experience.
Consistent Error Handling
MythIQ provides a consistent error format across all API endpoints, making it easier to implement robust error handling in your applications.
Error Response Format
All error responses from the API follow a consistent format:
{
"success": false,
"message": "A human-readable description of the error",
"code": "error_code",
// Additional fields may be included depending on the error type
"param": "parameter_name", // For validation errors
"retry_after": 30, // For rate limit errors
"request_id": "req_123abc" // For tracking and support
}
Error Fields
Field | Type | Description |
---|---|---|
success | boolean | Always false for error responses |
message | string | Human-readable description of the error |
code | string | Machine-readable error code |
param | string | Optional. The parameter that caused the error (for validation errors) |
retry_after | integer | Optional. Seconds to wait before retrying (for rate limit errors) |
request_id | string | Optional. Unique identifier for the request, useful for support |
HTTP Status Codes
The API uses the following HTTP status codes to indicate the result of a request:
Status Code | Description | Common Causes |
---|---|---|
200 OK | The request was successful | - |
400 Bad Request | The request was invalid or malformed | Missing required parameters, invalid parameter values |
401 Unauthorized | Authentication failed | Missing or invalid API key |
403 Forbidden | Permission denied | Insufficient permissions, account restrictions |
404 Not Found | The requested resource was not found | Invalid resource ID, deleted resource |
429 Too Many Requests | Rate limit exceeded | Too many requests in a given time period |
500 Internal Server Error | Server error | Unexpected server-side issues |
503 Service Unavailable | Service temporarily unavailable | Maintenance, temporary overload |
Error Codes
The API uses specific error codes to provide more detailed information about what went wrong. These codes are included in the code
field of the error response.
Authentication Errors
Error Code | Description | HTTP Status |
---|---|---|
authentication_error | Authentication failed | 401 |
invalid_api_key | The API key is invalid or has been revoked | 401 |
permission_error | The API key doesn't have permission for this action | 403 |
Validation Errors
Error Code | Description | HTTP Status |
---|---|---|
invalid_request | The request is invalid or malformed | 400 |
parameter_missing | A required parameter is missing | 400 |
parameter_invalid | A parameter has an invalid value | 400 |
content_too_large | The uploaded content exceeds size limits | 400 |
Resource Errors
Error Code | Description | HTTP Status |
---|---|---|
resource_not_found | The requested resource was not found | 404 |
model.notfound | The specified model was not found | 404 |
provider.notfound | The specified provider was not found | 404 |
Rate Limit Errors
Error Code | Description | HTTP Status |
---|---|---|
rate_limit_exceeded | Rate limit exceeded | 429 |
concurrent_limit_exceeded | Too many concurrent requests | 429 |
Generation Errors
Error Code | Description | HTTP Status |
---|---|---|
generation.failed | The generation process failed | 500 |
provider.incompatible | No compatible provider found for the request | 400 |
provider.exhausted | All available providers failed | 500 |
content_filtered | The request was filtered due to content policy | 400 |
Server Errors
Error Code | Description | HTTP Status |
---|---|---|
server_error | An unexpected server error occurred | 500 |
service_unavailable | The service is temporarily unavailable | 503 |
Error Handling Best Practices
Implementing proper error handling in your applications is essential for providing a good user experience. Here are some best practices for handling API errors:
Check for Success
Always check the success
field in the response to determine if the request was successful:
const response = await fetch('https://api.mythiq.ai/v1/images/generations', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY',
},
body: JSON.stringify({
model: 'stability/sdxl',
prompt: 'A beautiful sunset over the ocean',
}),
});
const data = await response.json();
if (!data.success) {
// Handle the error
console.error(`Error: ${data.message} (Code: ${data.code})`);
// Take appropriate action based on the error
} else {
// Process the successful response
console.log('Generated image:', data.data[0].url);
}
Implement Retry Logic
For transient errors like rate limits or temporary server issues, implement retry logic with exponential backoff:
async function makeRequestWithRetry(url, options, maxRetries = 3) {
let retries = 0;
while (retries < maxRetries) {
try {
const response = await fetch(url, options);
const data = await response.json();
if (!data.success) {
if (data.code === 'rate_limit_exceeded') {
// Rate limit error, wait and retry
const retryAfter = data.retry_after || 1;
console.log(`Rate limit exceeded. Retrying in ${retryAfter} seconds...`);
await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
retries++;
} else if (data.code === 'server_error' || data.code === 'service_unavailable') {
// Server error, retry with exponential backoff
retries++;
const backoffTime = Math.pow(2, retries) * 1000;
console.log(`Server error. Retrying in ${backoffTime / 1000} seconds...`);
await new Promise(resolve => setTimeout(resolve, backoffTime));
} else {
// Non-retryable error
return data;
}
} else {
// Success
return data;
}
} catch (error) {
// Network error or other exception
console.error('Request failed:', error);
retries++;
if (retries >= maxRetries) {
throw error;
}
// Exponential backoff
const backoffTime = Math.pow(2, retries) * 1000;
await new Promise(resolve => setTimeout(resolve, backoffTime));
}
}
throw new Error('Maximum retries exceeded');
}
Provide Meaningful Feedback
Translate API errors into user-friendly messages that help users understand what went wrong and how to fix it:
function getUserFriendlyErrorMessage(error) {
switch (error.code) {
case 'parameter_missing':
return `Missing required parameter: ${error.param}`;
case 'parameter_invalid':
return `Invalid value for parameter: ${error.param}`;
case 'rate_limit_exceeded':
return `Too many requests. Please try again in ${error.retry_after} seconds.`;
case 'model.notfound':
return 'The selected model is not available. Please choose a different model.';
case 'content_filtered':
return 'Your request was flagged by our content filter. Please modify your prompt.';
case 'authentication_error':
case 'invalid_api_key':
return 'Authentication failed. Please check your API key.';
default:
return `An error occurred: ${error.message}`;
}
}
Log Errors for Debugging
Log detailed error information for debugging purposes, including the request ID if available:
function logApiError(error, requestDetails) {
console.error('API Error:', {
code: error.code,
message: error.message,
requestId: error.request_id,
timestamp: new Date().toISOString(),
endpoint: requestDetails.url,
method: requestDetails.method,
// Include other relevant information
});
// You might also send this to your error tracking system
// errorTrackingService.captureException(error);
}
Getting Help
If you encounter persistent errors or need help troubleshooting an issue, there are several resources available:
Documentation
Check the relevant documentation pages for the endpoint you're using. Many common issues are addressed in the documentation.
Support
Contact our support team with the following information:
- The request ID from the error response (
request_id
) - The error code and message
- A description of what you were trying to do
- Any relevant code snippets or request details
Status Page
Check our status page for any ongoing incidents or maintenance that might be affecting the API.