""" Global Error Handling Middleware """ from fastapi import Request, status from fastapi.responses import JSONResponse from app.core.exceptions import ( NotFoundException, BusinessRuleException, ValidationException, AuthenticationException, AuthorizationException ) from app.core.logging import get_logger logger = get_logger(__name__) async def error_handler_middleware(request: Request, call_next): """ Global error handler for all exceptions """ try: return await call_next(request) except NotFoundException as e: logger.warning(f"Not found: {e.message}") return JSONResponse( status_code=status.HTTP_404_NOT_FOUND, content={"detail": e.message, "code": e.code} ) except BusinessRuleException as e: logger.warning(f"Business rule violation: {e.message}") return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content={"detail": e.message, "code": e.code} ) except ValidationException as e: logger.warning(f"Validation error: {e.message}") return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": e.message, "code": e.code} ) except AuthenticationException as e: logger.warning(f"Authentication error: {e.message}") return JSONResponse( status_code=status.HTTP_401_UNAUTHORIZED, content={"detail": e.message, "code": e.code} ) except AuthorizationException as e: logger.warning(f"Authorization error: {e.message}") return JSONResponse( status_code=status.HTTP_403_FORBIDDEN, content={"detail": e.message, "code": e.code} ) except Exception as e: logger.error(f"Unhandled exception: {str(e)}", exc_info=True) return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={"detail": "Internal server error"} )