Error Handling
Properly handling errors is crucial for building robust applications with the Arvae AI API. This guide covers common error types, how to parse error responses, and strategies for graceful error recovery.
Common Error Types
Error Type | Description | HTTP Status |
---|---|---|
authentication_error | Invalid or missing API key | 401 |
invalid_request_error | Malformed request, missing required parameters | 400 |
rate_limit_error | Too many requests in a given time period | 429 |
model_error | Issues with the specified model (not found, etc.) | 404/400 |
content_filter_error | Content violates usage policies | 400 |
server_error | Internal server error | 500 |
insufficient_credits | Account has insufficient credits for the request | 402 |
Error Response Format
When an error occurs, the API returns a JSON object with details about what went wrong:
Example Error Response
1{
2 "error": {
3 "message": "The model 'nonexistent-model' does not exist or you don't have access to it",
4 "type": "invalid_request_error",
5 "param": "model",
6 "code": "model_not_found"
7 }
8}
The error object contains the following fields:
Field | Description |
---|---|
message | Human-readable description of the error |
type | The error category (e.g., authentication_error, rate_limit_error) |
param | The parameter that caused the error (if applicable) |
code | A specific error code that can be used for more detailed error handling |
Handling Errors in Your Code
JavaScript Error Handling
1async function makeApiRequest() {
2 try {
3 const response = await fetch('https://arvae.ai/api/v1/chat/completions', {
4 method: 'POST',
5 headers: {
6 'Content-Type': 'application/json',
7 'Authorization': 'Bearer YOUR_API_KEY'
8 },
9 body: JSON.stringify({
10 model: 'openai/chatgpt-4o-latest',
11 messages: [
12 {role: 'user', content: 'Hello, who are you?'}
13 ]
14 })
15 });
16
17 // Check if the response is OK
18 if (!response.ok) {
19 const errorData = await response.json();
20
21 // Handle specific error types
22 if (response.status === 401) {
23 console.error('Authentication error:', errorData.error.message);
24 // Implement logic to refresh API key or prompt user to re-authenticate
25 } else if (response.status === 429) {
26 console.error('Rate limit exceeded:', errorData.error.message);
27 // Implement backoff strategy
28 await new Promise(resolve => setTimeout(resolve, 1000));
29 return makeApiRequest(); // Retry after delay
30 } else if (response.status === 402) {
31 console.error('Insufficient credits:', errorData.error.message);
32 // Redirect user to billing page or display a message
33 } else {
34 console.error('API error:', errorData.error.message);
35 // Generic error handling
36 }
37
38 throw new Error(errorData.error.message);
39 }
40
41 const data = await response.json();
42 return data;
43 } catch (error) {
44 // Handle network errors and other exceptions
45 console.error('Request failed:', error.message);
46 // Implement appropriate fallback behavior
47 throw error;
48 }
49}
Python Error Handling
1import requests
2import time
3from typing import Dict, Any
4
5def make_api_request(retries=3, backoff_factor=1.5) -> Dict[str, Any]:
6 """
7 Make a request to the Arvae API with error handling and retries.
8
9 Args:
10 retries: Maximum number of retry attempts
11 backoff_factor: Multiplicative factor for backoff between retries
12
13 Returns:
14 API response as a dictionary
15
16 Raises:
17 Exception: If the API request fails after all retries
18 """
19 url = "https://arvae.ai/api/v1/chat/completions"
20 headers = {
21 "Content-Type": "application/json",
22 "Authorization": f"Bearer YOUR_API_KEY"
23 }
24 data = {
25 "model": "openai/chatgpt-4o-latest",
26 "messages": [
27 {"role": "user", "content": "Hello, who are you?"}
28 ]
29 }
30
31 # Implement retry with exponential backoff
32 for attempt in range(retries):
33 try:
34 response = requests.post(url, headers=headers, json=data)
35
36 # Handle successful response
37 if response.status_code == 200:
38 return response.json()
39
40 # Handle error responses based on status code
41 if response.status_code == 401:
42 print(f"Authentication error: {response.json()['error']['message']}")
43 # Prompt for new API key or take appropriate action
44 raise Exception("Authentication failed")
45
46 elif response.status_code == 429:
47 error_data = response.json()
48 print(f"Rate limit exceeded: {error_data['error']['message']}")
49
50 # If this is not the last retry attempt, wait and retry
51 if attempt < retries - 1:
52 wait_time = backoff_factor ** attempt
53 print(f"Retrying in {wait_time} seconds...")
54 time.sleep(wait_time)
55 continue
56
57 elif response.status_code == 402:
58 print(f"Insufficient credits: {response.json()['error']['message']}")
59 # Redirect to billing page or display appropriate message
60 raise Exception("Insufficient credits")
61
62 else:
63 # Generic error handling for other status codes
64 error_data = response.json()
65 error_msg = error_data.get('error', {}).get('message', 'Unknown error')
66 error_type = error_data.get('error', {}).get('type', 'unknown')
67 print(f"API error ({error_type}): {error_msg}")
68
69 # For server errors (5xx), retry; for client errors (4xx), don't retry
70 if 500 <= response.status_code < 600 and attempt < retries - 1:
71 wait_time = backoff_factor ** attempt
72 print(f"Retrying in {wait_time} seconds...")
73 time.sleep(wait_time)
74 continue
75
76 raise Exception(f"API request failed: {error_msg}")
77
78 except requests.exceptions.RequestException as e:
79 # Handle network-level exceptions
80 print(f"Network error: {str(e)}")
81
82 if attempt < retries - 1:
83 wait_time = backoff_factor ** attempt
84 print(f"Retrying in {wait_time} seconds...")
85 time.sleep(wait_time)
86 continue
87
88 raise Exception(f"Network error after {retries} retries: {str(e)}")
89
90 raise Exception("API request failed after all retry attempts")
91
92# Usage example
93try:
94 response = make_api_request()
95 print("Success:", response['choices'][0]['message']['content'])
96except Exception as e:
97 print(f"Error: {str(e)}")
98 # Implement fallback behavior
Error Handling Best Practices
Implement Retry Logic
For transient errors like rate limits or server errors, implement a retry mechanism with exponential backoff to automatically recover from temporary issues.
1// Example retry function with exponential backoff
2async function retryWithBackoff(fn, maxRetries = 3, initialDelay = 1000) {
3 let retries = 0;
4
5 while (true) {
6 try {
7 return await fn();
8 } catch (error) {
9 if (retries >= maxRetries || !isRetryableError(error)) {
10 throw error;
11 }
12
13 const delay = initialDelay * Math.pow(2, retries);
14 console.log(`Retrying after ${delay}ms...`);
15 await new Promise(resolve => setTimeout(resolve, delay));
16 retries++;
17 }
18 }
19}
20
21// Helper to determine if an error is retryable
22function isRetryableError(error) {
23 // Retry on rate limits and server errors
24 return error.status === 429 || error.status >= 500;
25}
Implement Graceful Degradation
When the API is unavailable or returns errors, have fallback mechanisms to provide a degraded but functional experience:
- Cache previous successful responses and serve them when appropriate
- Switch to a less capable but more available model if the preferred one is unavailable
- Show pre-generated or static content when dynamic AI-generated content fails
- Clearly communicate to users when an error occurs and what they can expect
Monitor and Log Errors
Implement comprehensive error logging to track API error patterns. This helps identify recurring issues, understand user impact, and improve your application over time. Include request details (without sensitive data), error responses, and context to aid debugging.
Validate Inputs Before Sending
Prevent avoidable errors by validating user inputs and request parameters before sending them to the API. Check for required fields, correct data types, and reasonable values to catch errors early in your application.