Implementation:Cohere ai Cohere python ApiError
| Knowledge Sources | |
|---|---|
| Domains | SDK, Error Handling |
| Last Updated | 2026-02-15 14:00 GMT |
Overview
Custom exception class for API errors that captures HTTP status code, response headers, and response body.
Description
The ApiError class is a subclass of Python's built-in Exception and serves as the base error type raised when Cohere API calls return non-success HTTP responses. It stores the HTTP response headers, status code, and the parsed response body so that callers can inspect the full details of a failure. The class also provides a human-readable __str__ representation that includes all three attributes.
Usage
Catch ApiError in a try/except block around any Cohere SDK method call to handle API-level failures gracefully. Inspect the status_code attribute to branch on specific HTTP error codes and the body attribute to extract error messages returned by the API.
Code Reference
Source Location
- Repository: Cohere Python SDK
- File:
src/cohere/core/api_error.py
Signature
class ApiError(Exception):
headers: Optional[Dict[str, str]]
status_code: Optional[int]
body: Any
def __init__(
self,
*,
headers: Optional[Dict[str, str]] = None,
status_code: Optional[int] = None,
body: Any = None,
) -> None: ...
def __str__(self) -> str: ...
Import
from cohere.core.api_error import ApiError
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| headers | Optional[Dict[str, str]] | No | HTTP response headers returned by the API. Defaults to None. |
| status_code | Optional[int] | No | HTTP status code of the failed response. Defaults to None. |
| body | Any | No | Parsed response body containing error details. Defaults to None. |
Outputs
| Name | Type | Description |
|---|---|---|
| headers | Optional[Dict[str, str]] | The HTTP response headers stored on the exception instance. |
| status_code | Optional[int] | The HTTP status code stored on the exception instance. |
| body | Any | The parsed response body stored on the exception instance. |
| __str__() | str | Human-readable string in the format: headers: {...}, status_code: ..., body: ...
|
Usage Examples
import cohere
from cohere.core.api_error import ApiError
client = cohere.Client(api_key="your-api-key")
try:
response = client.v2.chat(
model="command-r-plus",
messages=[{"role": "user", "content": "Hello"}],
)
except ApiError as e:
print(f"API error {e.status_code}: {e.body}")
if e.status_code == 429:
print("Rate limited - retrying after backoff")