refactor: improve database middleware error handling

This commit is contained in:
YuehuCao 2025-10-22 11:53:24 +08:00
parent 21180ea017
commit 9d2ea5a838
2 changed files with 21 additions and 19 deletions

View File

@ -1,4 +1,4 @@
from fastapi import Request, status from fastapi import Request, status, HTTPException
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from webapi.middleware.freeleaps_auth_middleware import request_context_var from webapi.middleware.freeleaps_auth_middleware import request_context_var
from common.log.module_logger import ModuleLogger from common.log.module_logger import ModuleLogger
@ -58,14 +58,13 @@ class DatabaseMiddleware:
request.state.db = tenant_db request.state.db = tenant_db
request.state.product_id = product_id request.state.product_id = product_id
await self.module_logger.log_info(f"Successfully retrieved cached tenant database with Beanie for product_id: {product_id}") await self.module_logger.log_info(f"Successfully retrieved cached tenant database with Beanie for product_id: {product_id}")
return await self.app(scope, receive, send)
except HTTPException as e:
except ValueError as e: # Handle tenant not found or inactive (HTTPException from TenantDBCache)
# Handle tenant not found or inactive (ValueError from TenantDBCache) await self.module_logger.log_error(f"Tenant error for {product_id}: [{e.status_code}] {e.detail}")
await self.module_logger.log_error(f"Tenant error for {product_id}: {str(e)}")
response = JSONResponse( response = JSONResponse(
status_code=status.HTTP_404_NOT_FOUND, status_code=e.status_code,
content={"detail": str(e)} content={"detail": e.detail}
) )
return await response(scope, receive, send) return await response(scope, receive, send)
@ -75,4 +74,6 @@ class DatabaseMiddleware:
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"detail": "Database connection error"} content={"detail": "Database connection error"}
) )
return await response(scope, receive, send) return await response(scope, receive, send)
return await self.app(scope, receive, send)

View File

@ -1,4 +1,4 @@
from fastapi import Request, status from fastapi import Request, status, HTTPException
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from webapi.middleware.freeleaps_auth_middleware import request_context_var from webapi.middleware.freeleaps_auth_middleware import request_context_var
from common.log.module_logger import ModuleLogger from common.log.module_logger import ModuleLogger
@ -49,7 +49,7 @@ class DatabaseMiddleware:
request.state.product_id = None request.state.product_id = None
await self.module_logger.log_info(f"Successfully initialized main database with tenant models") await self.module_logger.log_info(f"Successfully initialized main database with tenant models")
return await self.app(scope, receive, send) return await self.app(scope, receive, send)
try: try:
# Get tenant-specific database with Beanie already initialized (cached) # Get tenant-specific database with Beanie already initialized (cached)
await self.module_logger.log_info(f"Attempting to get tenant database for product_id: {product_id}") await self.module_logger.log_info(f"Attempting to get tenant database for product_id: {product_id}")
@ -58,14 +58,13 @@ class DatabaseMiddleware:
request.state.db = tenant_db request.state.db = tenant_db
request.state.product_id = product_id request.state.product_id = product_id
await self.module_logger.log_info(f"Successfully retrieved cached tenant database with Beanie for product_id: {product_id}") await self.module_logger.log_info(f"Successfully retrieved cached tenant database with Beanie for product_id: {product_id}")
return await self.app(scope, receive, send)
except HTTPException as e:
except ValueError as e: # Handle tenant not found or inactive (HTTPException from TenantDBCache)
# Handle tenant not found or inactive (ValueError from TenantDBCache) await self.module_logger.log_error(f"Tenant error for {product_id}: [{e.status_code}] {e.detail}")
await self.module_logger.log_error(f"Tenant error for {product_id}: {str(e)}")
response = JSONResponse( response = JSONResponse(
status_code=status.HTTP_404_NOT_FOUND, status_code=e.status_code,
content={"detail": str(e)} content={"detail": e.detail}
) )
return await response(scope, receive, send) return await response(scope, receive, send)
@ -75,4 +74,6 @@ class DatabaseMiddleware:
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"detail": "Database connection error"} content={"detail": "Database connection error"}
) )
return await response(scope, receive, send) return await response(scope, receive, send)
return await self.app(scope, receive, send)