> ## Documentation Index
> Fetch the complete documentation index at: https://bilanc.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Error Handling

> Understanding API error responses and how to handle them

## 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 Response Format

Error responses include a detail message explaining the issue:

```json theme={null}
{
  "detail": "Error message"
}
```

For validation errors, the response includes more detailed information about the specific validation issues:

```json theme={null}
{
  "detail": [
    {
      "loc": ["body", "filters", "start_date"],
      "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

```json theme={null}
{
  "detail": "Not authenticated"
}
```

This error occurs when:

* The authentication token is missing
* The authentication token is invalid
* The authentication token has expired

### Invalid Parameters

```json theme={null}
{
  "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

```json theme={null}
{
  "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

```json theme={null}
{
  "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

```javascript theme={null}
const fetchMetrics = async () => {
  try {
    const response = await fetch('https://api.bilanc.co/metrics/cycle-time', {
      method: 'POST',
      headers: {
        'Authorization': 'YOUR_API_KEY',
        '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

```python theme={null}
import requests

def fetch_metrics():
    url = "https://api.bilanc.co/metrics/cycle-time"
    
    headers = {
        "Authorization": "YOUR_API_KEY",
        "Content-Type": "application/json"
    }
    
    payload = {
        "filters": {
            "repositories": [{"repository_name": "my-repo"}]
        },
        "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

1. **Always check status codes**: Don't assume that a request will succeed.
2. **Implement retry logic**: For transient errors (429, 500, etc.), implement a backoff strategy.
3. **Log detailed error information**: Include request details and response information for debugging.
4. **Provide user-friendly error messages**: Translate API errors into actionable information for users.
5. **Handle validation errors gracefully**: Parse the detailed validation error messages to help users fix their inputs.
6. **Monitor error rates**: Set up monitoring to track API errors and patterns.
7. **Contact support for persistent issues**: For recurring errors, contact Bilanc support with detailed information about the problem.
