Skip to content

Error Handling

HTTP Status Codes

Status CodeMeaningHandling Method
400Bad RequestCheck parameter format and values
401UnauthorizedCheck authentication information
429Too Many RequestsImplement retry mechanism, control request frequency
500Internal Server ErrorLog errors, retry later
503Service UnavailableImplement retry mechanism, set reasonable timeout

Common Error Types

1. Authentication Errors

Notice

If you receive a 401 Unauthorized error, please check if your API Key is correctly configured.

python
try:
    # API call
    response = requests.post(url, headers=headers, json=data)
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    if e.response.status_code == 401:
        print("Authentication failed, please check API Key")
    else:
        print(f"HTTP error: {e}")

2. Rate Limiting Errors

Notice

If you receive a 429 Too Many Requests error, please implement a backoff retry strategy.

python
import time

def api_call_with_retry(url, headers, data, max_retries=3):
    retries = 0
    while retries < max_retries:
        try:
            response = requests.post(url, headers=headers, json=data)
            if response.status_code == 429:
                wait_time = (2 ** retries) * 0.5  # Exponential backoff
                print(f"Too many requests, waiting {wait_time} seconds before retry")
                time.sleep(wait_time)
                retries += 1
                continue
            response.raise_for_status()
            return response
        except Exception as e:
            print(f"Error: {e}")
            retries += 1
            if retries >= max_retries:
                raise
    raise Exception("Maximum retry attempts exceeded")

3. Server Errors

Tip

For 5xx series errors, it's recommended to implement exponential backoff retry mechanism.

Best Practices

  1. Comprehensive Error Logging
  2. Implement Retry Mechanisms
  3. Graceful Degradation
  4. Monitoring and Alerting