Spaces:
Paused

yaz / src /core /error_handling.py
anaselamr's picture
[PLATFORM] fix(endpoints+templates): Sprint 52 — zero-error operational pass
579285c
Raw History Blame Contribute Delete
15.8 kB
"""
YAZ Care Platform - Enhanced Error Handling
Standardized error responses and retry logic
Every error response includes a ``correlation_id`` so support engineers can
trace faults end-to-end through structured logs.
Call ``setup_error_handlers(app)`` once in the application factory to register
all global exception handlers.
"""
import os
from typing import Optional, Dict, Any, Callable
from functools import wraps
import structlog
import traceback
from datetime import datetime, timezone
from enum import Enum
from fastapi import FastAPI, HTTPException, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from starlette.exceptions import HTTPException as StarletteHTTPException
logger = structlog.get_logger(__name__)
class ErrorCategory(str, Enum):
"""Error categories for better error classification"""
VALIDATION = "validation_error"
AUTHENTICATION = "authentication_error"
AUTHORIZATION = "authorization_error"
NOT_FOUND = "not_found_error"
CONFLICT = "conflict_error"
RATE_LIMIT = "rate_limit_error"
DATABASE = "database_error"
EXTERNAL_SERVICE = "external_service_error"
INTERNAL = "internal_server_error"
class ErrorDetail(BaseModel):
"""Detailed error information"""
category: ErrorCategory
message: str
user_message: str
field: Optional[str] = None
code: Optional[str] = None
details: Optional[Dict[str, Any]] = None
timestamp: str
request_id: Optional[str] = None
retry_after: Optional[int] = None
class StandardErrorResponse(BaseModel):
"""Standardized error response format"""
error: ErrorDetail
status_code: int
path: Optional[str] = None
def create_error_response(
category: ErrorCategory,
message: str,
user_message: str,
status_code: int = status.HTTP_500_INTERNAL_SERVER_ERROR,
field: Optional[str] = None,
code: Optional[str] = None,
details: Optional[Dict[str, Any]] = None,
request_id: Optional[str] = None,
retry_after: Optional[int] = None,
path: Optional[str] = None,
) -> JSONResponse:
"""
Create standardized error response.
The correlation_id is automatically pulled from the async context so
callers don't need to pass it explicitly.
"""
# Pull correlation ID from context (set by CorrelationIDMiddleware)
try:
from core.correlation import get_correlation_id
correlation_id: Optional[str] = get_correlation_id() or request_id
except ImportError:
correlation_id = request_id
# Never expose internal detail in production
is_prod = os.getenv("YAZ_ENV", "development") == "production"
safe_message = user_message if is_prod else message
error_content: Dict[str, Any] = {
"error": {
"code": code or category.value.upper(),
"message": safe_message,
"correlation_id": correlation_id,
"details": details or {},
"timestamp": datetime.now(timezone.utc).isoformat(),
}
}
if retry_after is not None:
error_content["error"]["retry_after"] = retry_after
if path:
error_content["error"]["path"] = path
return JSONResponse(status_code=status_code, content=error_content)
async def handle_validation_error(request: Request, exc: Exception) -> JSONResponse:
"""Handle validation errors"""
logger.warning(f"Validation error on {request.url.path}: {exc}")
return create_error_response(
category=ErrorCategory.VALIDATION,
message=str(exc),
user_message="The provided data is invalid. Please check your input and try again.",
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
path=str(request.url.path),
)
async def handle_not_found_error(request: Request, exc: Exception) -> JSONResponse:
"""Handle not found errors"""
logger.info(f"Resource not found: {request.url.path}")
return create_error_response(
category=ErrorCategory.NOT_FOUND,
message=str(exc),
user_message="The requested resource was not found.",
status_code=status.HTTP_404_NOT_FOUND,
path=str(request.url.path),
)
async def handle_http_exception(request: Request, exc: Exception) -> JSONResponse:
"""
Handle all Starlette/FastAPI HTTP exceptions with proper status codes.
Routes to appropriate category handler based on status code.
"""
from starlette.exceptions import HTTPException as StarletteHTTPException
# Get status code from exception
status_code = getattr(exc, "status_code", 500)
detail = getattr(exc, "detail", str(exc))
# Route to appropriate handler based on status code
if status_code == 401:
return create_error_response(
category=ErrorCategory.AUTHENTICATION,
message=str(detail),
user_message="Authentication failed. Please check your credentials.",
status_code=status_code,
path=str(request.url.path),
)
elif status_code == 403:
return create_error_response(
category=ErrorCategory.AUTHORIZATION,
message=str(detail),
user_message="You don't have permission to access this resource.",
status_code=status_code,
path=str(request.url.path),
)
elif status_code == 404:
return create_error_response(
category=ErrorCategory.NOT_FOUND,
message=str(detail),
user_message="The requested resource was not found.",
status_code=status_code,
path=str(request.url.path),
)
elif status_code == 409:
return create_error_response(
category=ErrorCategory.CONFLICT,
message=str(detail),
user_message="A conflict occurred with the current state of the resource.",
status_code=status_code,
path=str(request.url.path),
)
elif status_code == 422:
return create_error_response(
category=ErrorCategory.VALIDATION,
message=str(detail),
user_message="The provided data is invalid.",
status_code=status_code,
path=str(request.url.path),
)
elif status_code == 429:
return create_error_response(
category=ErrorCategory.RATE_LIMIT,
message=str(detail),
user_message="Too many requests. Please slow down.",
status_code=status_code,
path=str(request.url.path),
retry_after=60,
)
elif status_code >= 500:
logger.error(f"HTTP {status_code} error on {request.url.path}: {detail}")
return create_error_response(
category=ErrorCategory.INTERNAL,
message=str(detail),
user_message="An internal error occurred. Please try again later.",
status_code=status_code,
path=str(request.url.path),
)
else:
# Default handler for other status codes
logger.warning(f"HTTP {status_code} error on {request.url.path}: {detail}")
return create_error_response(
category=ErrorCategory.INTERNAL,
message=str(detail),
user_message="An error occurred.",
status_code=status_code,
path=str(request.url.path),
)
async def handle_authentication_error(request: Request, exc: Exception) -> JSONResponse:
"""Handle authentication errors"""
logger.warning(f"Authentication failed for {request.url.path}")
return create_error_response(
category=ErrorCategory.AUTHENTICATION,
message=str(exc),
user_message="Authentication failed. Please check your credentials and try again.",
status_code=status.HTTP_401_UNAUTHORIZED,
path=str(request.url.path),
)
async def handle_authorization_error(request: Request, exc: Exception) -> JSONResponse:
"""Handle authorization errors"""
logger.warning(f"Authorization failed for {request.url.path}")
return create_error_response(
category=ErrorCategory.AUTHORIZATION,
message=str(exc),
user_message="You don't have permission to access this resource.",
status_code=status.HTTP_403_FORBIDDEN,
path=str(request.url.path),
)
async def handle_database_error(request: Request, exc: Exception) -> JSONResponse:
"""Handle database errors"""
logger.error(f"Database error on {request.url.path}: {exc}")
return create_error_response(
category=ErrorCategory.DATABASE,
message="A database error occurred",
user_message="We're experiencing technical difficulties. Please try again later.",
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
path=str(request.url.path),
retry_after=30,
)
async def handle_internal_error(request: Request, exc: Exception) -> JSONResponse:
"""Handle internal server errors"""
logger.error(f"Internal error on {request.url.path}: {exc}\n{traceback.format_exc()}")
return create_error_response(
category=ErrorCategory.INTERNAL,
message="An internal server error occurred",
user_message="Something went wrong on our end. Our team has been notified.",
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
path=str(request.url.path),
)
def with_retry(max_attempts: int = 3, delay: float = 1.0, backoff: float = 2.0):
"""
Decorator to add retry logic to async functions
Args:
max_attempts: Maximum number of retry attempts
delay: Initial delay between retries (seconds)
backoff: Multiplier for delay after each attempt
"""
def decorator(func: Callable):
@wraps(func)
async def wrapper(*args, **kwargs):
last_exception = None
current_delay = delay
for attempt in range(1, max_attempts + 1):
try:
return await func(*args, **kwargs)
except Exception as e:
last_exception = e
if attempt < max_attempts:
logger.warning(
f"Attempt {attempt}/{max_attempts} failed for {func.__name__}: {e}. "
f"Retrying in {current_delay}s..."
)
await asyncio.sleep(current_delay)
current_delay *= backoff
else:
logger.error(f"All {max_attempts} attempts failed for {func.__name__}: {e}")
raise last_exception # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr]
return wrapper
return decorator
async def handle_request_validation_error(
request: Request, exc: RequestValidationError
) -> JSONResponse:
"""Handle Pydantic / FastAPI request validation errors (422)."""
fields = {}
for error in exc.errors():
loc = " → ".join(str(p) for p in error.get("loc", []))
fields[loc] = error.get("msg", "invalid value")
logger.warning("Validation error on %s: %s", request.url.path, fields)
return create_error_response(
category=ErrorCategory.VALIDATION,
message="Request validation failed",
user_message="The provided data is invalid. Please check your input.",
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
code="VALIDATION_ERROR",
details={"fields": fields},
path=str(request.url.path),
)
def setup_error_handlers(app: FastAPI) -> None:
"""
Register all global exception handlers on *app*.
Call once inside the application factory **after** all middleware is
attached so the handlers can read ``request.state.correlation_id``.
Example::
from core.error_handling import setup_error_handlers
setup_error_handlers(app)
"""
from sqlalchemy.exc import SQLAlchemyError
# ── Domain exception hierarchy (core.exceptions) ──────────────────────────
try:
from core.exceptions import (
YazNotFoundError,
YazAuthError,
YazPermissionError,
YazValidationError,
YazConflictError,
YazDatabaseError,
YazExternalServiceError,
YazException,
)
async def _handle_yaz(request: Request, exc: Exception) -> JSONResponse:
yaz = exc # type: ignore[assignment]
status_code = getattr(yaz, "status_code", 500)
code = getattr(yaz, "error_code", "INTERNAL_ERROR")
message = getattr(yaz, "message", str(exc))
detail = getattr(yaz, "detail", None)
category_map = {
404: ErrorCategory.NOT_FOUND,
401: ErrorCategory.AUTHENTICATION,
403: ErrorCategory.AUTHORIZATION,
422: ErrorCategory.VALIDATION,
409: ErrorCategory.CONFLICT,
503: ErrorCategory.DATABASE,
502: ErrorCategory.EXTERNAL_SERVICE,
}
category = category_map.get(status_code, ErrorCategory.INTERNAL)
return create_error_response(
category=category,
message=message,
user_message=message,
status_code=status_code,
code=code,
details=detail if isinstance(detail, dict) else None,
path=str(request.url.path),
)
app.add_exception_handler(YazNotFoundError, _handle_yaz) # type: ignore[arg-type]
app.add_exception_handler(YazAuthError, _handle_yaz) # type: ignore[arg-type]
app.add_exception_handler(YazPermissionError, _handle_yaz) # type: ignore[arg-type]
app.add_exception_handler(YazValidationError, _handle_yaz) # type: ignore[arg-type]
app.add_exception_handler(YazConflictError, _handle_yaz) # type: ignore[arg-type]
app.add_exception_handler(YazDatabaseError, _handle_yaz) # type: ignore[arg-type]
app.add_exception_handler(YazExternalServiceError, _handle_yaz) # type: ignore[arg-type]
app.add_exception_handler(YazException, _handle_yaz) # type: ignore[arg-type]
logger.info("Domain exception handlers registered (YazException hierarchy)")
except ImportError as _e:
logger.warning("core.exceptions not available — domain handlers skipped: %s", _e)
# ── Standard handlers ──────────────────────────────────────────────────────
app.add_exception_handler(RequestValidationError, handle_request_validation_error) # type: ignore[arg-type]
app.add_exception_handler(StarletteHTTPException, handle_http_exception) # type: ignore[arg-type]
app.add_exception_handler(HTTPException, handle_http_exception) # type: ignore[arg-type]
app.add_exception_handler(SQLAlchemyError, handle_database_error) # type: ignore[arg-type]
app.add_exception_handler(Exception, handle_internal_error) # type: ignore[arg-type]
logger.info("Global error handlers registered")
# Import asyncio for retry decorator
import asyncio
__all__ = [
"ErrorCategory",
"ErrorDetail",
"StandardErrorResponse",
"create_error_response",
"handle_validation_error",
"handle_request_validation_error",
"handle_not_found_error",
"handle_http_exception",
"handle_authentication_error",
"handle_authorization_error",
"handle_database_error",
"handle_internal_error",
"setup_error_handlers",
"with_retry",
]