35 lines
1.2 KiB
Python
35 lines
1.2 KiB
Python
from fastapi import FastAPI, Request
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from app.constants.result_code import ResultCode
|
|
from app.exception.err_exception import ErrException
|
|
from app.lib.response.admin_return import AdminReturn
|
|
|
|
|
|
async def err_exception_handler(request: Request, exc: ErrException) -> JSONResponse:
|
|
return JSONResponse(
|
|
status_code=200,
|
|
content=AdminReturn().error(exc.message, exc.code, exc.data),
|
|
)
|
|
|
|
|
|
async def validation_exception_handler(
|
|
request: Request,
|
|
exc: RequestValidationError,
|
|
) -> JSONResponse:
|
|
first_error = exc.errors()[0] if exc.errors() else {}
|
|
location = ".".join(str(item) for item in first_error.get("loc", []))
|
|
message = first_error.get("msg", "参数错误")
|
|
if location:
|
|
message = f"{location}: {message}"
|
|
return JSONResponse(
|
|
status_code=200,
|
|
content=AdminReturn().error(message, ResultCode.ERROR),
|
|
)
|
|
|
|
|
|
def register_exception_handlers(app: FastAPI) -> None:
|
|
app.add_exception_handler(ErrException, err_exception_handler)
|
|
app.add_exception_handler(RequestValidationError, validation_exception_handler)
|