This guide explains how to handle errors when using Sim APIs, including common error codes, troubleshooting steps, and code examples for proper error handling.
Errors vs. Warnings
Sim APIs distinguish between errors and warnings:
- Errors indicate that the request failed and could not be fulfilled. The API returns an error response with an HTTP 4xx or 5xx status code.
- Warnings indicate non-fatal issues where the request was partially fulfilled. The API returns a successful HTTP 200 response with data, but includes a
warnings array to inform you about issues that occurred.
When Warnings Occur
Warnings are currently used when you request data for specific chains via the chain_ids parameter and some of those chains are not supported. For example:
- If you request
?chain_ids=1,9999,10 and chain 9999 is not supported, the API will return data for chains 1 and 10, plus a warning about chain 9999.
When warnings are present, they appear in a warnings array within the successful (HTTP 200) response:
{
"wallet_address": "0x37305b1cd40574e4c5ce33f8e8306be057fd7341",
"balances": [...],
"warnings": [
{
"code": "UNSUPPORTED_CHAIN_IDS",
"message": "Some requested chain_ids are not supported. Balances are returned only for supported chains.",
"chain_ids": [9999, 77777777777],
"docs_url": "https://docs.sim.dune.com/evm/supported-chains"
}
]
}
Each warning includes:
code: A machine-readable warning code (e.g., UNSUPPORTED_CHAIN_IDS)
message: A human-readable description of the warning
chain_ids: The list of chain IDs that caused this warning (for chain-related warnings)
docs_url: A link to relevant documentation for more information
When an error occurs, Sim APIs return a JSON response with error information:
{
"error": "Description of what went wrong"
}
The error property can be either "error" or "message" depending on the type of error.
Common Error Codes
| HTTP Status | Description | Troubleshooting |
|---|
| 401 | Invalid or missing API key | Check that you’re including the correct API key in the X-Sim-Api-Key header |
| 400 | Malformed request | Verify the address format and other parameters in your request |
| 402 | Compute units quota exceeded | You are out of compute units. Please contact sales to upgrade your plan: [email protected] |
| 404 | Resource not found | Verify the endpoint URL and resource identifiers |
| 429 | Too many requests | Implement backoff strategies and consider upgrading your plan if you consistently hit limits |
| 500 | Server-side error | Retry the request after a short delay; if persistent, contact support |
Handling Warnings in Code
When processing API responses, check for the warnings array to be notified of non-fatal issues:
const response = await fetch('https://api.sim.dune.com/v1/evm/balances/0xd8da6bf26964af9d7eed9e03e53415d37aa96045?chain_ids=1,9999,10', {
headers: {'X-Sim-Api-Key': 'YOUR_API_KEY'}
});
const data = await response.json();
// Check for warnings
if (data.warnings && data.warnings.length > 0) {
data.warnings.forEach(warning => {
if (warning.code === 'UNSUPPORTED_CHAIN_IDS') {
console.warn(`Warning: Chains ${warning.chain_ids.join(', ')} are not supported.`);
console.warn(`See: ${warning.docs_url}`);
}
});
}
// Process the data that was successfully returned
console.log(`Found ${data.balances.length} balances`);
import requests
response = requests.get(
'https://api.sim.dune.com/v1/evm/balances/0xd8da6bf26964af9d7eed9e03e53415d37aa96045',
headers={'X-Sim-Api-Key': 'YOUR_API_KEY'},
params={'chain_ids': '1,9999,10'}
)
data = response.json()
# Check for warnings
if 'warnings' in data and len(data['warnings']) > 0:
for warning in data['warnings']:
if warning['code'] == 'UNSUPPORTED_CHAIN_IDS':
print(f"Warning: Chains {warning['chain_ids']} are not supported.")
print(f"See: {warning['docs_url']}")
# Process the data that was successfully returned
print(f"Found {len(data['balances'])} balances")
Handling Errors in Code
Here are examples of how to properly handle errors in different programming languages:
fetch('https://api.sim.dune.com/v1/evm/balances/0xd8da6bf26964af9d7eed9e03e53415d37aa96045', {
method: 'GET',
headers: {'X-Sim-Api-Key': 'YOUR_API_KEY'}
})
.then(response => {
if (!response.ok) {
return response.json().then(err => {
const errorMessage = err.error || err.message || response.statusText;
throw new Error(`API error: ${errorMessage}`);
});
}
return response.json();
})
.then(data => {
console.log('Success:', data);
// Process your data here
})
.catch(err => {
console.error('Error fetching balances:', err);
// Handle error appropriately in your application
// e.g., show user-friendly message, retry, or fallback behavior
});
import requests
import time
def get_balances(address, api_key, max_retries=3):
url = f"https://api.sim.dune.com/v1/evm/balances/{address}"
headers = {"X-Sim-Api-Key": api_key}
for attempt in range(max_retries):
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # Raises an exception for 4XX/5XX responses
return response.json()
except requests.exceptions.HTTPError as err:
status_code = err.response.status_code
error_data = {}
try:
error_data = err.response.json()
except:
pass
# Get error message from either 'error' or 'message' property
error_message = error_data.get('error') or error_data.get('message', 'Unknown error')
print(f"HTTP Error {status_code}: {error_message}")
# Handle specific error codes
if status_code == 429: # Rate limit exceeded
wait_time = min(2 ** attempt, 60) # Exponential backoff
print(f"Rate limit exceeded. Retrying in {wait_time} seconds...")
time.sleep(wait_time)
continue
elif status_code == 500: # Server error
if attempt < max_retries - 1:
wait_time = 2 ** attempt
print(f"Server error. Retrying in {wait_time} seconds...")
time.sleep(wait_time)
continue
# For other errors or if we've exhausted retries
return {"error": error_message, "status_code": status_code}
except requests.exceptions.RequestException as err:
print(f"Request error: {err}")
return {"error": "Network or connection error", "details": str(err)}
return {"error": "Max retries exceeded"}
# Usage
result = get_balances("0xd8da6bf26964af9d7eed9e03e53415d37aa96045", "YOUR_API_KEY")
if "error" in result:
print(f"Failed to get balances: {result['error']}")
else:
print(f"Found {len(result['balances'])} token balances")
Best Practices for Error Handling
-
Always check for errors: Don’t assume API calls will succeed.
-
Use HTTP status codes: Rely on HTTP status codes rather than parsing error message strings for programmatic decisions.
-
Implement retry logic with backoff: For transient errors (like rate limits or server errors), implement exponential backoff.
-
Provide meaningful error messages: Transform API error responses into user-friendly messages.
-
Log errors for debugging: Maintain detailed logs of API errors for troubleshooting.
-
Implement fallbacks: When possible, have fallback behavior when API calls fail.
Debugging Tips
If you’re experiencing persistent errors:
-
Verify your API key: Ensure it’s valid and has the necessary permissions.
-
Check request format: Validate that your request parameters match the API specifications.
-
Inspect full error responses: The error message often contains specific details about what went wrong.
-
Monitor your usage: Check if you’re approaching or exceeding rate limits.
-
Test with cURL: Isolate issues by testing the API directly with cURL:
curl -v -X GET "https://api.sim.dune.com/v1/evm/balances/0xd8da6bf26964af9d7eed9e03e53415d37aa96045" \
-H "X-Sim-Api-Key: YOUR_API_KEY"
Need More Help?
If you’re still experiencing issues after following these guidelines, please reach out through our support channels.