chain-rdeveloper portal
build

Error Tracking

Overview

Comprehensive error tracking and handling is crucial for maintaining system reliability and providing excellent user experience in the Chainr platform.

Error Handling Architecture

Global Exception Handlers

from fastapi import HTTPException, Request
from fastapi.responses import JSONResponse
import logging

logger = logging.getLogger(__name__)

@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    # Log HTTP exceptions with context
    logger.warning(
        "HTTP exception occurred",
        extra={
            "status_code": exc.status_code,
            "detail": exc.detail,
            "url": str(request.url),
            "method": request.method,
            "client_ip": request.client.host,
            "user_agent": request.headers.get("user-agent")
        }
    )

    return JSONResponse(
        status_code=exc.status_code,
        content={"detail": exc.detail, "type": "http_exception"}
    )

@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
    # Log unexpected errors with full context
    logger.error(
        "Unexpected error occurred",
        exc_info=True,
        extra={
            "url": str(request.url),
            "method": request.method,
            "client_ip": request.client.host,
            "user_id": getattr(request.state, 'user_id', None)
        }
    )

    # Send to error tracking service
    await send_to_error_tracker(exc, request)

    return JSONResponse(
        status_code=500,
        content={"detail": "Internal server error", "type": "server_error"}
    )

Error Classification

HTTP Status Codes

  • 400 Bad Request: Validation errors, malformed requests

  • 401 Unauthorized: Missing/invalid authentication

  • 403 Forbidden: Insufficient permissions

  • 404 Not Found: Resource doesn't exist

  • 409 Conflict: Resource state conflicts

  • 422 Unprocessable Entity: Business logic validation failures

  • 429 Too Many Requests: Rate limiting

  • 500 Internal Server Error: Unexpected server errors

  • 502 Bad Gateway: Upstream service failures

  • 503 Service Unavailable: Service temporarily unavailable

Custom Error Types

from enum import Enum

class ErrorType(Enum):
    VALIDATION_ERROR = "validation_error"
    AUTHENTICATION_ERROR = "authentication_error"
    AUTHORIZATION_ERROR = "authorization_error"
    RESOURCE_NOT_FOUND = "resource_not_found"
    RESOURCE_CONFLICT = "resource_conflict"
    EXTERNAL_SERVICE_ERROR = "external_service_error"
    DATABASE_ERROR = "database_error"
    RATE_LIMIT_ERROR = "rate_limit_error"

class ChainrException(Exception):
    def __init__(self, message: str, error_type: ErrorType, status_code: int = 500, details: dict = None):
        self.message = message
        self.error_type = error_type
        self.status_code = status_code
        self.details = details or {}
        super().__init__(self.message)

Error Tracking Integration

Sentry Integration

import sentry_sdk
from sentry_sdk.integrations.fastapi import FastAPIIntegration
from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration

sentry_sdk.init(
    dsn=os.getenv("SENTRY_DSN"),
    environment=os.getenv("ENVIRONMENT", "development"),
    integrations=[
        FastAPIIntegration(),
        SqlalchemyIntegration(),
    ],
    # Capture performance data
    traces_sample_rate=0.1,
    # Capture context
    send_default_pii=False,
    # Error filtering
    before_send=before_send_filter
)

def before_send_filter(event, hint):
    # Filter out sensitive information
    if 'request' in event:
        # Remove sensitive headers
        headers = event['request'].get('headers', {})
        sensitive_headers = ['authorization', 'x-api-key', 'cookie']
        for header in sensitive_headers:
            headers.pop(header, None)

    return event

Custom Error Tracking

import aiohttp
import json

async def send_to_error_tracker(exception: Exception, request: Request):
    error_data = {
        "message": str(exception),
        "type": type(exception).__name__,
        "timestamp": datetime.utcnow().isoformat(),
        "service": "chainr-core",
        "version": "1.0.0",
        "request": {
            "method": request.method,
            "url": str(request.url),
            "headers": dict(request.headers),
            "client_ip": request.client.host,
            "user_agent": request.headers.get("user-agent")
        },
        "context": {
            "user_id": getattr(request.state, 'user_id', None),
            "project_id": getattr(request.state, 'project_id', None),
            "trace_id": getattr(request.state, 'trace_id', None)
        },
        "stack_trace": traceback.format_exc()
    }

    # Remove sensitive data
    error_data = sanitize_error_data(error_data)

    async with aiohttp.ClientSession() as session:
        try:
            async with session.post(
                "https://error-tracker.chainr.com/api/errors",
                json=error_data,
                headers={"Authorization": f"Bearer {os.getenv('ERROR_TRACKER_KEY')}"}
            ) as response:
                if response.status != 200:
                    logger.error(f"Failed to send error to tracker: {response.status}")
        except Exception as e:
            logger.error(f"Error tracker communication failed: {e}")

Error Response Format

Standardized Error Responses

{
  "error": {
    "type": "validation_error",
    "message": "Invalid input data",
    "details": {
      "field": "email",
      "reason": "Invalid email format"
    },
    "code": "VALIDATION_ERROR",
    "timestamp": "2024-01-01T12:00:00Z",
    "request_id": "req-12345",
    "suggestions": ["Please provide a valid email address"]
  }
}

Validation Error Details

from pydantic import BaseModel, ValidationError

class ValidationErrorResponse(BaseModel):
    type: str = "validation_error"
    message: str
    details: dict
    code: str = "VALIDATION_ERROR"

@app.exception_handler(ValidationError)
async def validation_exception_handler(request: Request, exc: ValidationError):
    errors = {}
    for error in exc.errors():
        field = ".".join(str(loc) for loc in error["loc"])
        errors[field] = error["msg"]

    return JSONResponse(
        status_code=422,
        content=ValidationErrorResponse(
            message="Validation failed",
            details=errors
        ).dict()
    )

Error Monitoring & Alerting

Error Rate Monitoring

from prometheus_client import Counter, Gauge

error_counter = Counter(
    'chainr_errors_total',
    'Total errors by type',
    ['service', 'error_type', 'endpoint']
)

error_rate_gauge = Gauge(
    'chainr_error_rate',
    'Current error rate percentage',
    ['service', 'time_window']
)

# Track errors
def track_error(error_type: str, endpoint: str):
    error_counter.labels(
        service='core',
        error_type=error_type,
        endpoint=endpoint
    ).inc()

Alerting Rules

groups:
  - name: chainr_errors
    rules:
      - alert: HighErrorRate
        expr: rate(chainr_errors_total[5m]) > 10
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "Error rate is critically high"

      - alert: DatabaseErrors
        expr: rate(chainr_errors_total{error_type="database_error"}[5m]) > 5
        for: 1m
        labels:
          severity: warning
        annotations:
          summary: "Database errors detected"

Error Recovery & Resilience

Retry Logic

import asyncio
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type

@retry(
    stop=stop_after_attempt(3),
    wait=wait_exponential(multiplier=1, min=4, max=10),
    retry=retry_if_exception_type((aiohttp.ClientError, sqlalchemy.exc.OperationalError))
)
async def call_external_service(url: str, data: dict):
    async with aiohttp.ClientSession() as session:
        async with session.post(url, json=data) as response:
            response.raise_for_status()
            return await response.json()

Circuit Breaker Pattern

from circuitbreaker import circuit

@circuit(failure_threshold=5, recovery_timeout=60)
async def call_ai_service(prompt: str):
    # AI service call that might fail
    async with aiohttp.ClientSession() as session:
        async with session.post("http://svc-ai:5000/generate", json={"prompt": prompt}) as response:
            if response.status >= 500:
                raise Exception("AI service error")
            return await response.json()

User-Friendly Error Messages

Error Message Guidelines

  • Use clear, non-technical language

  • Provide actionable suggestions

  • Include relevant context

  • Avoid exposing internal system details

Localized Error Messages

ERROR_MESSAGES = {
    "en": {
        "VALIDATION_ERROR": "Please check your input and try again.",
        "AUTHENTICATION_ERROR": "Please log in to continue.",
        "RESOURCE_NOT_FOUND": "The requested item could not be found.",
        "RATE_LIMIT_ERROR": "Too many requests. Please wait and try again."
    },
    "es": {
        "VALIDATION_ERROR": "Por favor verifica tu entrada e intenta de nuevo.",
        "AUTHENTICATION_ERROR": "Por favor inicia sesión para continuar.",
        "RESOURCE_NOT_FOUND": "El elemento solicitado no pudo ser encontrado.",
        "RATE_LIMIT_ERROR": "Demasiadas solicitudes. Por favor espera e intenta de nuevo."
    }
}

def get_error_message(error_type: str, language: str = "en") -> str:
    return ERROR_MESSAGES.get(language, ERROR_MESSAGES["en"]).get(error_type, "An error occurred.")

Error Analysis & Prevention

Error Pattern Analysis

  • Identify common error scenarios

  • Implement preventive measures

  • Improve error messages based on user feedback

  • Monitor error resolution times

Root Cause Analysis

  • Correlate errors with system metrics

  • Analyze error spikes and patterns

  • Implement fixes for recurring issues

  • Update monitoring based on findings

Testing Error Scenarios

def test_error_handling():
    # Test validation errors
    response = client.post("/api/projects", json={"name": ""})
    assert response.status_code == 422

    # Test authentication errors
    response = client.get("/api/user/profile")
    assert response.status_code == 401

    # Test not found errors
    response = client.get("/api/projects/99999")
    assert response.status_code == 404