Error Handling¶
For Publishers: Ensuring Smooth Integration¶
As a publisher integrating Mosaic into your AI, proper error handling is crucial to ensure a seamless user experience. This guide will help you implement robust error handling for your Mosaic API integration.
Important for Publishers
Always implement graceful fallbacks when errors occur. Your users should never see raw error messages or experience disruptions in their AI interactions.
Error Response Format¶
All API errors from Mosaic are returned in a consistent JSON format:
Common Error Scenarios¶
-
Authentication Issues
Problems with your API key or authentication headers -
Invalid Requests
Missing required parameters or malformed requests -
No Matching Ads
No advertisements match the provided keywords -
Server Errors
Temporary issues with the Mosaic infrastructure
HTTP Status Codes¶
HTTP Status Code | Description | Possible Cause | Publisher Action |
---|---|---|---|
400 | Bad Request | Missing required parameters or invalid request format | Check that your request includes both conversation and context_keywords |
404 | Not Found | Invalid API key or no matching advertisements found | Verify your API key and try with different keywords |
429 | Too Many Requests | Rate limit exceeded | Implement request throttling |
500 | Internal Server Error | Database error or server issue | Implement retry logic with exponential backoff |
503 | Service Unavailable | Temporary outage or maintenance | Retry after a delay |
Specific Error Messages¶
Authentication Errors¶
Publisher Solution: Ensure you're including the mosaic-api-key
header in all requests.
Publisher Solution: Verify your API key is correct and that your model hasn't been deactivated.
Request Validation Errors¶
Publisher Solution: Ensure both the conversation
and context_keywords
fields are included in your request body.
No Matching Ads¶
Publisher Solution: This is a common scenario when no ads match the provided keywords. Your application should continue normally without displaying an ad.
Implementation Examples¶
JavaScript Error Handling Example¶
async function fetchAdWithErrorHandling(conversation, keywords) {
try {
const response = await fetch('https://demo.xmosaic.ai/api/fetch-ads', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'mosaic-api-key': process.env.MOSAIC_API_KEY
},
body: JSON.stringify({
conversation,
context_keywords: keywords
})
});
// Handle HTTP errors
if (!response.ok) {
// For 404 errors (no matching ads), just return null
if (response.status === 404) {
console.log('No matching ads found for keywords:', keywords);
return null;
}
// For 5xx errors, throw an error to trigger retry logic
if (response.status >= 500) {
throw new Error(`Server error: ${response.status}`);
}
// For other errors, log and return null
console.error(`API error: ${response.status}`);
return null;
}
const data = await response.json();
return data.advertisements[0]; // Get the first advertisement
} catch (error) {
console.error('Error fetching ad:', error);
return null; // Return null for any error
}
}
Retry Logic Example¶
async function fetchAdWithRetry(conversation, keywords, maxRetries = 3) {
let retries = 0;
while (retries < maxRetries) {
try {
const response = await fetch('https://demo.xmosaic.ai/api/fetch-ads', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'mosaic-api-key': process.env.MOSAIC_API_KEY
},
body: JSON.stringify({
conversation,
context_keywords: keywords
})
});
// For 404 (no ads), just return null without retrying
if (response.status === 404) {
return null;
}
// For other non-200 responses, throw to trigger retry
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const data = await response.json();
return data.advertisements[0];
} catch (error) {
retries++;
if (retries >= maxRetries) {
console.error('Max retries reached for Mosaic API');
return null;
}
// Exponential backoff: 2^retries * 100ms
const delay = Math.pow(2, retries) * 100;
console.log(`Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
return null;
}
Error Handling Best Practices¶
1. Graceful Degradation¶
Always design your integration so that if the Mosaic API is unavailable or returns an error, your AI model continues to function normally without ads.
async function getAIResponseWithAd(userMessage) {
// First, get the AI response
const aiResponse = await generateAIResponse(userMessage);
try {
// Then try to get an ad
const ad = await fetchAdWithRetry(userMessage, extractKeywords(userMessage));
// If we got an ad, append it to the response
if (ad) {
return `${aiResponse}\n\n${ad.campaign_markdown}`;
}
} catch (error) {
// Log the error but don't let it affect the user experience
console.error('Error fetching ad:', error);
}
// If no ad or there was an error, just return the AI response
return aiResponse;
}
2. Implement Retry Logic¶
For 5xx errors (server errors), implement retry logic with exponential backoff to handle temporary issues:
- First retry: Wait 200ms
- Second retry: Wait 400ms
- Third retry: Wait 800ms
3. Log Errors for Debugging¶
Log errors with enough context to help with debugging:
console.error('Mosaic API error:', {
status: error.status,
message: error.message,
keywords: keywords,
timestamp: new Date().toISOString()
});
4. Monitor Error Rates¶
Set up monitoring to track error rates and be alerted if they exceed normal thresholds.
Reporting Issues to Mosaic¶
If you encounter persistent errors or unexpected behavior, please contact Mosaic support with the following information:
- API Key: First 4 characters only (never share your full API key)
- Account email: Your Mosaic account email
- Request Payload: The request body you sent (with any sensitive information removed)
- Error Response: The complete error response you received
- Timestamp: When the error occurred
- Reproduction Steps: Any steps to reproduce the issue
- Frequency: How often the error occurs
Contact Mosaic support at maaps@xmosaic.ai