Skip to main content

Overview

The Mention SDK provides a hierarchy of exception classes to help you handle different types of errors gracefully. All exceptions inherit from the base MentionError class, making it easy to catch all SDK-related errors or handle specific error types.

Exception Hierarchy

MentionError (base)
├── MentionAPIError
│   ├── MentionAuthError
│   ├── MentionNotFoundError
│   └── MentionRateLimitError
├── MentionValidationError
└── MentionConnectionError

Exception Classes

MentionError

Base exception for all Mention API errors. All other exceptions inherit from this class. Properties:
  • message (str): The error message
  • details (dict): Additional error details
When raised:
  • Base class for all SDK exceptions
  • Can be used to catch all Mention SDK errors
Example:
from mention import MentionClient, MentionError

client = MentionClient(api_key="your_api_key")

try:
    account = client.accounts.get("account_id")
except MentionError as e:
    # Catches all Mention SDK errors
    print(f"Error: {e.message}")
    print(f"Details: {e.details}")

MentionAPIError

Exception raised when the API returns an error response. Properties:
  • message (str): The error message
  • status_code (int): HTTP status code from the API response
  • response_body (dict | str | None): The full response body from the API
  • details (dict): Contains status_code and response keys
When raised:
  • API returns a 4xx or 5xx status code
  • Server errors or client errors not covered by specific subclasses
Example:
from mention import MentionClient, MentionAPIError

client = MentionClient(api_key="your_api_key")

try:
    mention = client.mentions.create(
        alert_id="alert_id",
        title="Mention title"
    )
except MentionAPIError as e:
    print(f"API Error: {e.message}")
    print(f"Status Code: {e.status_code}")
    print(f"Response: {e.response_body}")

MentionAuthError

Exception raised for authentication and authorization errors (401, 403). Properties:
  • Inherits all properties from MentionAPIError
  • status_code (int): Will be 401 or 403
When raised:
  • Invalid or missing API key (401)
  • Insufficient permissions to access a resource (403)
  • Expired authentication token
Example:
from mention import MentionClient, MentionAuthError

try:
    client = MentionClient(api_key="invalid_key")
    accounts = client.accounts.list()
except MentionAuthError as e:
    print(f"Authentication failed: {e.message}")
    print(f"Status: {e.status_code}")
    # Prompt user to check their API key

MentionNotFoundError

Exception raised when a resource is not found (404). Properties:
  • Inherits all properties from MentionAPIError
  • status_code (int): Will be 404
When raised:
  • Requested resource doesn’t exist
  • Invalid resource ID
  • Resource was deleted
Example:
from mention import MentionClient, MentionNotFoundError

client = MentionClient(api_key="your_api_key")

try:
    alert = client.alerts.get("non_existent_alert_id")
except MentionNotFoundError as e:
    print(f"Resource not found: {e.message}")
    # Handle missing resource gracefully

MentionRateLimitError

Exception raised when the API rate limit is exceeded (429). Properties:
  • Inherits all properties from MentionAPIError
  • status_code (int): Will be 429
  • retry_after (int | None): Number of seconds to wait before retrying (if provided by API)
When raised:
  • Too many requests sent in a given time period
  • API rate limit exceeded
Example:
import time
from mention import MentionClient, MentionRateLimitError

client = MentionClient(api_key="your_api_key")

try:
    mentions = client.mentions.list(alert_id="alert_id")
except MentionRateLimitError as e:
    print(f"Rate limit exceeded: {e.message}")
    if e.retry_after:
        print(f"Retry after {e.retry_after} seconds")
        time.sleep(e.retry_after)
        # Retry the request
    else:
        # Use exponential backoff
        time.sleep(60)

MentionValidationError

Exception raised for request validation errors. Properties:
  • Inherits all properties from MentionError
  • message (str): Validation error description
  • details (dict): Additional validation error details
When raised:
  • Invalid parameter values
  • Missing required parameters
  • Data format validation failures
  • Client-side validation errors before making API request
Example:
from mention import MentionClient, MentionValidationError

client = MentionClient(api_key="your_api_key")

try:
    alert = client.alerts.create(
        name="",  # Invalid: empty name
        sources=["invalid_source"]
    )
except MentionValidationError as e:
    print(f"Validation error: {e.message}")
    print(f"Details: {e.details}")
    # Fix the validation issues and retry

MentionConnectionError

Exception raised for network and connection errors. Properties:
  • Inherits all properties from MentionError
  • message (str): Connection error description
  • details (dict): Additional connection error details
When raised:
  • Network connectivity issues
  • Timeout errors
  • DNS resolution failures
  • Connection refused errors
  • SSL/TLS errors
Example:
from mention import MentionClient, MentionConnectionError

client = MentionClient(api_key="your_api_key")

try:
    accounts = client.accounts.list()
except MentionConnectionError as e:
    print(f"Connection error: {e.message}")
    # Check network connectivity or retry

Practical Error Handling Patterns

Catch All SDK Errors

from mention import MentionClient, MentionError

client = MentionClient(api_key="your_api_key")

try:
    alert = client.alerts.get("alert_id")
except MentionError as e:
    print(f"SDK Error: {e}")

Handle Specific Error Types

from mention import (
    MentionClient,
    MentionAuthError,
    MentionNotFoundError,
    MentionRateLimitError,
    MentionAPIError,
    MentionError
)

client = MentionClient(api_key="your_api_key")

try:
    mentions = client.mentions.list(alert_id="alert_id", page=1, limit=100)
except MentionAuthError as e:
    # Handle authentication errors
    print(f"Authentication failed: {e.message}")
    # Redirect to login or request new API key
except MentionNotFoundError as e:
    # Handle missing resources
    print(f"Alert not found: {e.message}")
    # Show user-friendly message
except MentionRateLimitError as e:
    # Handle rate limiting
    print(f"Rate limit exceeded")
    if e.retry_after:
        print(f"Wait {e.retry_after} seconds before retrying")
except MentionAPIError as e:
    # Handle other API errors
    print(f"API error ({e.status_code}): {e.message}")
except MentionError as e:
    # Handle any other SDK errors
    print(f"Unexpected error: {e}")

Retry Logic with Rate Limiting

import time
from mention import MentionClient, MentionRateLimitError, MentionConnectionError

client = MentionClient(api_key="your_api_key")

def fetch_mentions_with_retry(alert_id, max_retries=3):
    """Fetch mentions with automatic retry on rate limit and connection errors."""
    retries = 0
    
    while retries < max_retries:
        try:
            return client.mentions.list(alert_id=alert_id)
        except MentionRateLimitError as e:
            retries += 1
            wait_time = e.retry_after if e.retry_after else (2 ** retries)
            print(f"Rate limited. Waiting {wait_time}s before retry {retries}/{max_retries}")
            time.sleep(wait_time)
        except MentionConnectionError as e:
            retries += 1
            wait_time = 2 ** retries
            print(f"Connection error. Waiting {wait_time}s before retry {retries}/{max_retries}")
            time.sleep(wait_time)
    
    raise Exception(f"Failed after {max_retries} retries")

# Usage
try:
    mentions = fetch_mentions_with_retry("alert_id")
    print(f"Fetched {len(mentions)} mentions")
except Exception as e:
    print(f"Failed to fetch mentions: {e}")

Logging Errors for Debugging

import logging
from mention import MentionClient, MentionAPIError, MentionError

logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger(__name__)

client = MentionClient(api_key="your_api_key")

try:
    account = client.accounts.get("account_id")
except MentionAPIError as e:
    logger.error(
        "API error occurred",
        extra={
            "status_code": e.status_code,
            "message": e.message,
            "response": e.response_body,
            "details": e.details
        }
    )
    raise
except MentionError as e:
    logger.error(
        "SDK error occurred",
        extra={
            "message": e.message,
            "details": e.details
        }
    )
    raise

Graceful Degradation

from mention import (
    MentionClient,
    MentionNotFoundError,
    MentionConnectionError,
    MentionError
)

client = MentionClient(api_key="your_api_key")

def get_alert_safely(alert_id, default=None):
    """Get alert with graceful fallback on errors."""
    try:
        return client.alerts.get(alert_id)
    except MentionNotFoundError:
        print(f"Alert {alert_id} not found, using default")
        return default
    except MentionConnectionError:
        print("Network error, using cached data")
        return default
    except MentionError as e:
        print(f"Error fetching alert: {e.message}")
        return default

# Usage
alert = get_alert_safely("alert_id", default={"name": "Default Alert"})

Best Practices

  1. Catch specific exceptions first: Order your except clauses from most specific to most general
  2. Always handle authentication errors: Check API keys and permissions when MentionAuthError occurs
  3. Respect rate limits: Use retry_after property from MentionRateLimitError to implement proper backoff
  4. Log error details: Include status_code, response_body, and details in your logs for debugging
  5. Implement retry logic: Handle transient errors like MentionConnectionError with exponential backoff
  6. Validate input early: Catch MentionValidationError and provide user-friendly feedback
  7. Use the base exception for catch-all: Use MentionError to catch all SDK-related errors

Build docs developers (and LLMs) love