feat: Improve exception handling for openrouterkey endpoint with enhanced path checks and logging

This commit is contained in:
Slipstream 2025-05-14 17:41:29 -06:00
parent f5cfa7a00a
commit 161707f71d
Signed by: slipstream
GPG Key ID: 13E498CE010AC6FD

View File

@ -402,21 +402,34 @@ app = FastAPI(title="Unified API Service", lifespan=lifespan, debug=True)
@app.exception_handler(StarletteHTTPException)
async def teapot_override(request: Request, exc: StarletteHTTPException):
# Check if this is a request to an openrouterkey endpoint (case-insensitive check for 'openrouterkey' part)
path_lower = str(request.url.path).lower() # Ensure path is string and lowercased
is_openrouterkey_related_path = (
path_lower == "/openrouterkey" or
path_lower == "/api/openrouterkey" or
path_lower == "/discordapi/openrouterkey"
)
# Use request.scope['path'] for a more direct path representation and ensure it's lowercased.
# It's possible request.url.path might have subtle differences in some edge cases.
try:
# The path from the scope is usually the most reliable raw path.
request_path_from_scope = request.scope.get('path', "")
path_lower = request_path_from_scope.lower()
except Exception as e:
# Fallback in case scope or path is unusual, though highly unlikely.
log.error(f"Error accessing request.scope['path'] in teapot_override: {e}, falling back to request.url.path")
path_lower = str(request.url.path).lower()
if is_openrouterkey_related_path:
# For openrouterkey related paths, log the actual exception and re-raise it.
# This means if it's a 404, it stays a 404. If it's 403, it stays 403, etc.
log.warning(f"Exception for openrouterkey path '{request.url.path}': {exc.status_code} - {exc.detail}")
# Define the specific openrouterkey paths that should not be converted to 418 on a 404.
# These are the exact paths where the endpoints are mounted.
exact_openrouterkey_paths = [
"/openrouterkey",
"/api/openrouterkey",
"/discordapi/openrouterkey"
]
if path_lower in exact_openrouterkey_paths:
# For these specific openrouterkey paths, log the actual exception and re-raise it.
# This ensures that a 404 (e.g., route truly not found, or handler raises 404),
# or any other error like 403 (Forbidden) or 500 (Server Error from handler)
# is passed through as is.
log.warning(f"Exception for specific openrouterkey path '{request_path_from_scope}': {exc.status_code} - {exc.detail}")
raise exc # Re-raise the original exception
# For all other paths that result in a 404:
# For all other paths, if a 404 occurs, convert it to a 418 teapot response.
if exc.status_code == 404:
log.info(f"Converting 404 to 418 teapot for path: {request.url.path}")
html_content = """