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

# Handling Errors Effectively

> Guidance on SDK error categories, communicating errors to users, logging best practices, and general exception handling for robust server development.

Robust error handling is crucial for a good user experience and stable operation of your monetized MCP Server. When interacting with the AgentPay SDK, anticipate potential issues and plan how your server will respond.

## AgentPay SDK Call Errors

Calls to `agentpay_client.consume()` and `agentpay_client.validate_api_key()` can result in errors. The primary way to check for these is by inspecting the `success` attribute (or `is_valid` for validation) of the result object and then using the `error_code` and `error_message` for details.

### Key Error Categories & Handling:

1. **User-Related Errors (Actionable by the User):**
   * **Insufficient Funds** (`INSUFFICIENT_FUNDS` from `consume()`):
     * **Action:** Deny access to the paid tool/feature.
     * **User Communication:** Clearly inform the user that the operation could not be completed due to insufficient funds. Direct them to the AgentPay Hub to top up their balance.
     * **Server Response:** Return an appropriate HTTP status code (e.g., 402 Payment Required) and a structured error message.
   * **Invalid/Inactive API Key** (`INVALID_API_KEY` from `consume()` or `validate_api_key()`):
     * **Action:** Deny access.
     * **User Communication:** Inform the user that their API key is invalid, expired, or deactivated. Direct them to AgentPay Hub to check their key status or obtain a new one.
     * **Server Response:** Return an HTTP status code (e.g., 401 Unauthorized or 403 Forbidden) and a structured error message.

2. **Configuration/Server-Side Errors (Potentially Actionable by You):**
   * **Invalid Service Token** (This might manifest as persistent failures on all SDK calls, or a specific error during client initialization):
     * **Action:** If this occurs, your server cannot communicate with AgentPay. Log this critical error.
     * **User Communication:** Users might see generic "service unavailable" or "payment system error" messages. Avoid exposing raw SDK errors about service tokens to end-users.
     * **Developer Action:** Verify your `AGENTPAY_SERVICE_TOKEN` environment variable is correct and the AgentPay Hub shows your server as active.
   * **(Placeholder: Add other server-side error codes if the SDK can produce them, e.g., `SERVER_RATE_LIMITED` if AgentPay applies rate limits to service token usage.)**

3. **Network/Transient Errors:**
   * SDK calls might fail due to temporary network issues between your server and AgentPay.
   * **Action:** Implement a retry strategy for `consume()` calls, **especially using the same `usage_event_id` for idempotency**. For `validate_api_key()`, retries might also be appropriate depending on the context.
   * **Retry Logic:** Consider exponential backoff for retries. Do not retry indefinitely.
   * **User Communication:** If retries fail, inform the user of a temporary issue and suggest trying again later.
   * **Logging:** Log these errors to monitor the stability of the connection to AgentPay.

### General SDK Exception Handling:

Wrap your AgentPay SDK calls in `try...except` blocks to catch any unexpected exceptions that might arise from the SDK itself (e.g., issues with underlying HTTP libraries, unexpected response parsing errors).

```python theme={null}
# Example for consume()
try:
    consumption_result = agentpay_client.consume(...)
    if consumption_result.success:
        # ... proceed ...
    else:
        # ... handle specific consumption_result.error_code ...
except Exception as e:
    # Log this unexpected SDK error
    print(f"Unexpected AgentPay SDK error: {e}")
    # Return a generic error to the user
    # raise HTTPException(status_code=503, detail="Payment service temporarily unavailable.")
```

## Communicating Errors to Client Users

* **Be Clear and Actionable:** When an error occurs that the user can resolve (e.g., insufficient funds, invalid API key), provide clear instructions on what they need to do.
* **Use Appropriate HTTP Status Codes:** Align your server's responses with standard HTTP semantics (e.g., 401, 402, 403, 500, 503).
* **Structured Error Responses:** Return errors in a consistent format (e.g., JSON with `error`, `message`, `details` fields) that client applications can parse and handle.
* **Avoid Exposing Sensitive Details:** Do not send raw stack traces or overly technical internal error messages (especially related to your Service Token or AgentPay infrastructure) to the end-user.

## Logging

* **Successful Consumptions:** Consider logging successful consumption events (e.g., `usage_event_id`, `user_id` (if available on your end), `amount_cents`) for your own auditing and records, though AgentPay Hub will be your primary source of truth for billing.
* **Failed Consumptions:** Always log failed consumption attempts with the `api_key` (or a non-sensitive part of it), `error_code`, `error_message`, and `usage_event_id` for debugging and support.
* **SDK Exceptions:** Log any unexpected exceptions from the SDK calls.
* **Security of Logs:** Ensure your logs do not contain full User API Keys or your Service Token unless absolutely necessary for very short-term, secure debugging, and ensure log storage is secure.

## Next Steps

* Review [Best Practices for Security](./security) when handling API keys and service tokens.
* Understand how to define [Pricing Models & Freemium](../platform/pricing-models) options.
