MythIQ

Command Palette

Search for a command to run...

API Errors

Learn about the error responses from the MythIQ API and how to handle them effectively.

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:

json
{
  "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

FieldTypeDescription
successbooleanAlways false for error responses
messagestringHuman-readable description of the error
codestringMachine-readable error code
paramstringOptional. The parameter that caused the error (for validation errors)
retry_afterintegerOptional. Seconds to wait before retrying (for rate limit errors)
request_idstringOptional. 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 CodeDescriptionCommon Causes
200 OKThe request was successful-
400 Bad RequestThe request was invalid or malformedMissing required parameters, invalid parameter values
401 UnauthorizedAuthentication failedMissing or invalid API key
403 ForbiddenPermission deniedInsufficient permissions, account restrictions
404 Not FoundThe requested resource was not foundInvalid resource ID, deleted resource
429 Too Many RequestsRate limit exceededToo many requests in a given time period
500 Internal Server ErrorServer errorUnexpected server-side issues
503 Service UnavailableService temporarily unavailableMaintenance, 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 CodeDescriptionHTTP Status
authentication_errorAuthentication failed401
invalid_api_keyThe API key is invalid or has been revoked401
permission_errorThe API key doesn't have permission for this action403

Validation Errors

Error CodeDescriptionHTTP Status
invalid_requestThe request is invalid or malformed400
parameter_missingA required parameter is missing400
parameter_invalidA parameter has an invalid value400
content_too_largeThe uploaded content exceeds size limits400

Resource Errors

Error CodeDescriptionHTTP Status
resource_not_foundThe requested resource was not found404
model.notfoundThe specified model was not found404
provider.notfoundThe specified provider was not found404

Rate Limit Errors

Error CodeDescriptionHTTP Status
rate_limit_exceededRate limit exceeded429
concurrent_limit_exceededToo many concurrent requests429

Generation Errors

Error CodeDescriptionHTTP Status
generation.failedThe generation process failed500
provider.incompatibleNo compatible provider found for the request400
provider.exhaustedAll available providers failed500
content_filteredThe request was filtered due to content policy400

Server Errors

Error CodeDescriptionHTTP Status
server_errorAn unexpected server error occurred500
service_unavailableThe service is temporarily unavailable503

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:

typescript
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:

typescript
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:

typescript
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:

typescript
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.