feat: enhance error handling with custom HTTP exception responses and middleware improvements
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
import logging
|
||||
import time
|
||||
from typing import Callable
|
||||
from fastapi import HTTPException, Request, Response
|
||||
from fastapi import Request, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from .config import settings
|
||||
from .database import CoreSessionLocal
|
||||
@@ -34,9 +35,13 @@ class TenantMiddleware(BaseHTTPMiddleware):
|
||||
# 4. Validación estricta de Token (solo para lo que no es público ni OPTIONS)
|
||||
auth_header = request.headers.get("Authorization")
|
||||
if not auth_header or not auth_header.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Missing or invalid authorization header"
|
||||
return JSONResponse(
|
||||
status_code=401,
|
||||
content={
|
||||
"error": "HTTP_ERROR",
|
||||
"message": "Missing or invalid authorization header",
|
||||
"status_code": 401,
|
||||
}
|
||||
)
|
||||
|
||||
token = auth_header.split(" ")[1]
|
||||
@@ -48,7 +53,14 @@ class TenantMiddleware(BaseHTTPMiddleware):
|
||||
request.state.user_info = user_info
|
||||
except Exception as e:
|
||||
logger.error(f"❌ Tenant validation error: {str(e)}")
|
||||
raise HTTPException(status_code=401, detail="Invalid authentication")
|
||||
return JSONResponse(
|
||||
status_code=401,
|
||||
content={
|
||||
"error": "HTTP_ERROR",
|
||||
"message": "Invalid authentication",
|
||||
"status_code": 401,
|
||||
}
|
||||
)
|
||||
|
||||
# 5. Continuar con la petición real
|
||||
return await call_next(request)
|
||||
@@ -104,19 +116,28 @@ class LicenseValidationMiddleware(BaseHTTPMiddleware):
|
||||
license_info = license_service.validate_license(tenant_id)
|
||||
|
||||
if not license_info["is_valid"]:
|
||||
raise HTTPException(
|
||||
return JSONResponse(
|
||||
status_code=402,
|
||||
detail=f"License validation failed: {license_info['reason']}",
|
||||
content={
|
||||
"error": "HTTP_ERROR",
|
||||
"message": f"License validation failed: {license_info['reason']}",
|
||||
"status_code": 402,
|
||||
}
|
||||
)
|
||||
|
||||
# Agregar info de licencia al request state
|
||||
request.state.license_info = license_info
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"License validation error: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail="License validation error")
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={
|
||||
"error": "HTTP_ERROR",
|
||||
"message": "License validation error",
|
||||
"status_code": 500,
|
||||
}
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user