5.9 KiB
5.9 KiB
Exceptions
The SDK provides specific exceptions for different error types. All exceptions inherit from the base FastGPTError.
Exception Hierarchy
FastGPTError
├── APIError
├── AuthenticationError
├── RateLimitError
├── ValidationError
└── StreamParseError
Exception Types
FastGPTError
Base exception class for all FastGPT SDK errors.
from fastgpt_client.exceptions import FastGPTError
try:
# SDK operation
pass
except FastGPTError as e:
print(f"FastGPT error: {e}")
APIError
General API error for 4xx and 5xx responses that don't have a specific exception type.
from fastgpt_client.exceptions import APIError
try:
response = client.create_chat_completion(...)
except APIError as e:
print(f"API error: {e.message}")
print(f"Status code: {e.status_code}")
print(f"Response data: {e.response_data}")
Attributes:
| Attribute | Type | Description |
|---|---|---|
message |
str |
Error message |
status_code |
int |
HTTP status code |
response_data |
`dict | None` |
AuthenticationError
Raised when authentication fails (401 status code).
from fastgpt_client.exceptions import AuthenticationError
try:
response = client.create_chat_completion(...)
except AuthenticationError as e:
print(f"Authentication failed: {e.message}")
print("Please check your API key")
Common Causes:
- Invalid API key
- Missing API key
- Expired API key
- API key format incorrect
RateLimitError
Raised when rate limit is exceeded (429 status code).
from fastgpt_client.exceptions import RateLimitError
try:
response = client.create_chat_completion(...)
except RateLimitError as e:
print(f"Rate limit exceeded: {e.message}")
if e.retry_after:
print(f"Retry after {e.retry_after} seconds")
Attributes:
| Attribute | Type | Description |
|---|---|---|
message |
str |
Error message |
retry_after |
`str | None` |
status_code |
int |
HTTP status code (429) |
response_data |
`dict | None` |
ValidationError
Raised when request validation fails (422 status code).
from fastgpt_client.exceptions import ValidationError
try:
response = client.create_chat_completion(
messages=[{"role": "user", "content": "Hello"}],
invalid_param="value"
)
except ValidationError as e:
print(f"Validation error: {e.message}")
print(f"Response data: {e.response_data}")
Common Causes:
- Invalid parameter values
- Missing required parameters
- Incorrect parameter types
- Invalid message format
StreamParseError
Raised when parsing streaming responses fails.
from fastgpt_client.exceptions import StreamParseError
try:
for line in response.iter_lines():
# Parse streaming data
pass
except StreamParseError as e:
print(f"Stream parsing error: {e.message}")
Comprehensive Error Handling
from fastgpt_client import ChatClient
from fastgpt_client.exceptions import (
APIError,
AuthenticationError,
RateLimitError,
ValidationError,
FastGPTError
)
def safe_chat_completion(client, messages):
"""Handle chat completion with comprehensive error handling."""
try:
response = client.create_chat_completion(
messages=messages,
stream=False
)
response.raise_for_status()
return response.json()
except AuthenticationError:
print("Error: Invalid API key. Please check your credentials.")
return None
except RateLimitError as e:
print(f"Error: Rate limit exceeded. Please wait.")
if e.retry_after:
print(f"Retry after {e.retry_after} seconds")
return None
except ValidationError as e:
print(f"Error: Invalid request parameters: {e.message}")
return None
except APIError as e:
print(f"Error: API request failed: {e.message}")
return None
except FastGPTError as e:
print(f"Error: Unexpected FastGPT error: {e}")
return None
except Exception as e:
print(f"Error: Unexpected error: {e}")
return None
# Usage
with ChatClient(api_key="fastgpt-xxxxx") as client:
result = safe_chat_completion(
client,
[{"role": "user", "content": "Hello!"}]
)
Error Handling Best Practices
- Always handle exceptions when making API calls
- Use specific exceptions for better error handling
- Log errors for debugging purposes
- Provide user-friendly messages based on error type
- Implement retry logic for rate limit errors
- Validate parameters before making API calls
Retry Logic for Rate Limiting
import time
from fastgpt_client import ChatClient
from fastgpt_client.exceptions import RateLimitError
def chat_with_retry(client, messages, max_retries=3):
"""Retry chat completion on rate limit errors."""
for attempt in range(max_retries):
try:
response = client.create_chat_completion(
messages=messages,
stream=False
)
response.raise_for_status()
return response.json()
except RateLimitError as e:
if attempt < max_retries - 1:
# Use Retry-After header or default delay
delay = int(e.retry_after) if e.retry_after else 5
print(f"Rate limited. Waiting {delay} seconds...")
time.sleep(delay)
else:
print(f"Max retries exceeded. Giving up.")
raise
Next Steps
- Error Handling Guide - More error handling strategies
- Rate Limiting - Handling rate limits effectively