Error Handling
The Bilanc Metrics API returns standard HTTP status codes to indicate success or failure of an API request.
HTTP Status Codes
Status Code | Description |
---|
200 OK | Request successful |
400 Bad Request | Invalid request parameters |
401 Unauthorized | Authentication failed |
403 Forbidden | Insufficient permissions |
404 Not Found | Requested resource not found |
422 Unprocessable Entity | Request validation failed |
429 Too Many Requests | Rate limit exceeded |
500 Internal Server Error | Server-side error |
Error responses include a detail message explaining the issue:
{
"detail": "Error message"
}
For validation errors, the response includes more detailed information about the specific validation issues:
{
"detail": [
{
"loc": ["body", "filters", "repository_id"],
"msg": "field required",
"type": "value_error.missing"
},
{
"loc": ["body", "date_level"],
"msg": "value is not a valid enumeration member; permitted: 'day', 'week', 'month', 'quarter', 'year'",
"type": "type_error.enum",
"ctx": {
"enum_values": ["day", "week", "month", "quarter", "year"]
}
}
]
}
Common Error Scenarios
Authentication Errors
{
"detail": "Not authenticated"
}
This error occurs when:
- The authentication token is missing
- The authentication token is invalid
- The authentication token has expired
Invalid Parameters
{
"detail": [
{
"loc": ["body", "filters", "start_date"],
"msg": "invalid date format. Expected format: YYYY-MM-DD",
"type": "value_error.date"
}
]
}
This error occurs when:
- Required parameters are missing
- Parameters have invalid values
- Parameters have invalid formats
Resource Not Found
{
"detail": "Metric type 'unknown-metric' not found"
}
This error occurs when:
- The requested metric type doesn’t exist
- The specified resource ID doesn’t exist
Server Errors
{
"detail": "Internal server error"
}
This error occurs when:
- The server encounters an unexpected condition
- A dependency service is unavailable
Handling Errors in Your Applications
JavaScript Example
const fetchMetrics = async () => {
try {
const response = await fetch('https://api.bilanc.co/metrics/v2/cycle-time', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_AUTH_TOKEN',
'Content-Type': 'application/json'
},
body: JSON.stringify({
filters: {
repository_id: "123456"
},
date_level: "month"
})
});
if (!response.ok) {
const errorData = await response.json();
// Handle different error types
switch (response.status) {
case 400:
console.error('Invalid request parameters:', errorData.detail);
break;
case 401:
console.error('Authentication failed. Please check your API token.');
break;
case 429:
console.error('Rate limit exceeded. Please try again later.');
break;
case 500:
console.error('Server error. Please try again later or contact support.');
break;
default:
console.error('API error:', errorData.detail);
}
throw new Error(`API error: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching metrics:', error);
throw error;
}
};
Python Example
import requests
def fetch_metrics():
url = "https://api.bilanc.co/metrics/v2/cycle-time"
headers = {
"Authorization": "Bearer YOUR_AUTH_TOKEN",
"Content-Type": "application/json"
}
payload = {
"filters": {
"repository_id": "123456"
},
"date_level": "month"
}
try:
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status() # Raise exception for 4XX/5XX responses
return response.json()
except requests.exceptions.HTTPError as e:
error_msg = "Unknown error"
if response.headers.get("content-type") == "application/json":
try:
error_data = response.json()
if "detail" in error_data:
error_msg = error_data["detail"]
except:
pass
# Handle different error types
if response.status_code == 400:
print(f"Invalid request parameters: {error_msg}")
elif response.status_code == 401:
print("Authentication failed. Please check your API token.")
elif response.status_code == 429:
print("Rate limit exceeded. Please try again later.")
elif response.status_code == 500:
print("Server error. Please try again later or contact support.")
else:
print(f"API error ({response.status_code}): {error_msg}")
raise
except Exception as e:
print(f"Error fetching metrics: {str(e)}")
raise
Best Practices for Error Handling
- Always check status codes: Don’t assume that a request will succeed.
- Implement retry logic: For transient errors (429, 500, etc.), implement a backoff strategy.
- Log detailed error information: Include request details and response information for debugging.
- Provide user-friendly error messages: Translate API errors into actionable information for users.
- Handle validation errors gracefully: Parse the detailed validation error messages to help users fix their inputs.
- Monitor error rates: Set up monitoring to track API errors and patterns.
- Contact support for persistent issues: For recurring errors, contact Bilanc support with detailed information about the problem.
Responses are generated using AI and may contain mistakes.