add exception_handlers module

This commit is contained in:
grillazz 2025-08-24 15:36:02 +02:00
parent ee637b53e0
commit 9c7db17da8
2 changed files with 19 additions and 11 deletions

View File

@ -1,34 +1,43 @@
# app/exception_handlers/base.py
import orjson import orjson
from fastapi import Request from fastapi import Request
from fastapi.responses import JSONResponse
from rotoger import AppStructLogger from rotoger import AppStructLogger
from attrs import define, field
logger = AppStructLogger().get_logger() logger = AppStructLogger().get_logger()
@define(slots=True)
class RequestInfo:
"""Contains extracted request information."""
path: str = field()
body: dict = field(default=None)
@define(slots=True)
class BaseExceptionHandler: class BaseExceptionHandler:
"""Base class for all exception handlers with common functionality.""" """Base class for all exception handlers with common functionality."""
@staticmethod @staticmethod
async def extract_request_info(request: Request): async def extract_request_info(request: Request) -> RequestInfo:
"""Extract common request information.""" """Extract common request information."""
request_path = request.url.path request_path = request.url.path
request_body = None
try: try:
raw_body = await request.body() raw_body = await request.body()
request_body = orjson.loads(raw_body) if raw_body else None if raw_body:
request_body = orjson.loads(raw_body)
except orjson.JSONDecodeError: except orjson.JSONDecodeError:
request_body = None pass
return request_path, request_body return RequestInfo(path=request_path, body=request_body)
@classmethod @classmethod
async def log_error(cls, message, request_info, **kwargs): async def log_error(cls, message: str, request_info: RequestInfo, **kwargs):
"""Log error with standardized format.""" """Log error with standardized format."""
request_path, request_body = request_info
await logger.aerror( await logger.aerror(
message, message,
request_url=request_path, request_url=request_info.path,
request_body=request_body, request_body=request_info.body,
**kwargs **kwargs
) )

View File

@ -1,7 +1,6 @@
from fastapi import Request from fastapi import Request
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.exc import SQLAlchemyError
from app.exception_handlers.base import BaseExceptionHandler from app.exception_handlers.base import BaseExceptionHandler