# handlers.py import traceback from fastapi import Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from starlette.exceptions import HTTPException as StarletteHTTPException from actions.system.exceptions import BusinessRuleException from actions.log.log import Log def register_exception_handlers(app): def __init__(self): log = Log() @app.exception_handler(BusinessRuleException) async def business_rule_exception_handler( request: Request, exc: BusinessRuleException ): response = {"status": "422", "error": "Regra de negócio", "detail": exc.message} # Salva o log em disco Log.register(response, "storage/temp/business_rule_exception_handler.json") return JSONResponse(status_code=422, content=response) @app.exception_handler(StarletteHTTPException) async def http_exception_handler(request: Request, exc: StarletteHTTPException): response = { "status": exc.status_code, "error": "HTTP Error", "detail": exc.detail, } # Salva o log em disco Log.register(response, "storage/temp/http_exception_handler.json") return JSONResponse(status_code=exc.status_code, content=response) @app.exception_handler(RequestValidationError) async def validation_exception_handler( request: Request, exc: RequestValidationError ): response = {"status": 400, "error": "Erro de validação", "detail": exc.errors()} # Salva o log em disco Log.register(response, "storage/temp/validation_exception_handler.json") return JSONResponse(status_code=400, content=response) @app.exception_handler(Exception) async def global_exception_handler(request: Request, exc: Exception): response = { "status": 500, "error": "Erro Interno do Servidor", "type": type(exc).__name__, "message": str(exc), "trace": traceback.format_exc(), } # Salva o log em disco Log.register(response, "storage/temp/validation_exception_handler.json") return JSONResponse(status_code=500, content=response)