study / api /errors.py
xiaolongmr
添加编辑
638cad0
Raw History Blame Contribute Delete
2.24 kB
from __future__ import annotations
from fastapi import FastAPI, Request
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from services.protocol.error_response import anthropic_error_response, openai_error_response
from utils.sensitive_data import sanitize_sensitive_data
def _is_openai_compatible_path(path: str) -> bool:
return path == "/v1" or path.startswith("/v1/")
def _is_anthropic_messages_path(path: str) -> bool:
return path == "/v1/messages"
def _compatible_error_response(
request: Request,
detail: object,
status_code: int,
headers: dict[str, str] | None = None,
) -> JSONResponse:
if _is_anthropic_messages_path(request.url.path):
return anthropic_error_response(detail, status_code, headers=headers)
return openai_error_response(detail, status_code, headers=headers)
def install_exception_handlers(app: FastAPI) -> None:
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse:
if _is_openai_compatible_path(request.url.path):
return _compatible_error_response(request, exc.detail, exc.status_code, exc.headers)
return JSONResponse(
status_code=exc.status_code,
content={
"detail": sanitize_sensitive_data(
jsonable_encoder(exc.detail),
drop_personal_fields=True,
)
},
headers=exc.headers,
)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
if _is_openai_compatible_path(request.url.path):
return _compatible_error_response(request, exc.errors(), 422)
return JSONResponse(
status_code=422,
content={
"detail": sanitize_sensitive_data(
jsonable_encoder(exc.errors()),
drop_personal_fields=True,
)
},
)