Understanding and handling API errors effectively
When an error occurs, the Omni API returns an appropriate HTTP status code and a JSON response with details about the error. The error response has the following format:
{
"error": {
"code": "error_code",
"message": "Detailed error message"
}
}The API uses standard HTTP status codes to indicate the success or failure of a request:
| Status Code | Description |
|---|---|
| 200 OK | The request was successful |
| 400 Bad Request | The request was invalid or malformed |
| 401 Unauthorized | Authentication is required (missing API key) |
| 403 Forbidden | The API key is invalid or doesn't have permission to access the requested resource |
| 404 Not Found | The requested resource doesn't exist |
| 429 Too Many Requests | Rate limit exceeded |
| 500 Internal Server Error | An error occurred on the server |
The code field in the error response provides a machine-readable identifier for the error. Here are some common error codes:
| Error Code | Description |
|---|---|
| missing_api_key | The API key is missing from the request |
| invalid_api_key | The API key is invalid or has been revoked |
| rate_limit_exceeded | The rate limit for the API key has been exceeded |
| invalid_request | The request is invalid or malformed |
| invalid_input | The input data is invalid or missing required fields |
| content_limit_exceeded | The content exceeds the maximum allowed size |
| server_error | An error occurred on the server |
{
"error": {
"code": "missing_api_key",
"message": "API key is required. Please include an X-API-Key header."
}
}{
"error": {
"code": "invalid_api_key",
"message": "The provided API key is invalid or has been revoked."
}
}{
"error": {
"code": "rate_limit_exceeded",
"message": "Rate limit exceeded. Please try again later."
}
}{
"error": {
"code": "invalid_request",
"message": "The request body is not valid JSON."
}
}{
"error": {
"code": "invalid_input",
"message": "The 'input' field is required and must be an array."
}
}{
"error": {
"code": "content_limit_exceeded",
"message": "The text content exceeds the maximum allowed length of 10,000 characters."
}
}Here are some examples of how to handle errors in your code:
async function moderateContent(apiKey, input) {
try {
const response = await fetch('https://api.omnimoderate.com/v1/moderate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': apiKey
},
body: JSON.stringify({ input })
});
// Parse the response as JSON
const data = await response.json();
// Check if the response is an error
if (!response.ok) {
// Handle the error based on the status code and error code
switch (response.status) {
case 400:
console.error('Bad Request:', data.error.message);
// Handle invalid request
break;
case 401:
console.error('Unauthorized:', data.error.message);
// Handle missing API key
break;
case 403:
console.error('Forbidden:', data.error.message);
// Handle invalid API key
break;
case 429:
console.error('Rate Limit Exceeded:', data.error.message);
// Implement retry logic with exponential backoff
break;
case 500:
console.error('Server Error:', data.error.message);
// Handle server error
break;
default:
console.error('Error:', data.error.message);
// Handle other errors
}
throw new Error(data.error.message);
}
// Return the successful response
return data;
} catch (error) {
// Handle network errors or other exceptions
console.error('Error moderating content:', error.message);
throw error;
}
}import requests
def moderate_content(api_key, input_data):
try:
response = requests.post(
'https://api.omnimoderate.com/v1/moderate',
headers={
'Content-Type': 'application/json',
'X-API-Key': api_key
},
json={'input': input_data}
)
# Parse the response as JSON
data = response.json()
# Check if the response is an error
if response.status_code != 200:
# Handle the error based on the status code and error code
if response.status_code == 400:
print(f"Bad Request: {data['error']['message']}")
# Handle invalid request
elif response.status_code == 401:
print(f"Unauthorized: {data['error']['message']}")
# Handle missing API key
elif response.status_code == 403:
print(f"Forbidden: {data['error']['message']}")
# Handle invalid API key
elif response.status_code == 429:
print(f"Rate Limit Exceeded: {data['error']['message']}")
# Implement retry logic with exponential backoff
elif response.status_code == 500:
print(f"Server Error: {data['error']['message']}")
# Handle server error
else:
print(f"Error: {data['error']['message']}")
# Handle other errors
raise Exception(data['error']['message'])
# Return the successful response
return data
except requests.exceptions.RequestException as e:
# Handle network errors or other exceptions
print(f"Error moderating content: {str(e)}")
raise