FastAPI 具有出色的异常处理功能,因此您可以通过多种方式自定义异常。
您可以引发 HTTPException,HTTPException 是一个普通的 Python 异常,带有与 API 相关的附加数据。但是你不能返回它你需要引发它,因为它是一个 Python 异常
from fastapi import HTTPException
...
@app.get("/")
async def hello(name: str):
if not name:
raise HTTPException(status_code=404, detail="Name field is required")
return {"Hello": name}
通过添加name: str
为查询参数,它会自动成为必需的,因此您需要添加Optional
from typing import Optional
...
@app.get("/")
async def hello(name: Optional[str] = None):
error = {"Error": "Name field is required"}
if name:
return {"Hello": name}
return error
$ curl 127.0.0.1:8000/?name=imbolc
{"Hello":"imbolc"}
...
$ curl 127.0.0.1:8000
{"Error":"Name field is required"}
但在你的情况下,我认为这是处理 FastAPI 中的错误的最佳方法,覆盖validation_exception_handler
:
from fastapi import FastAPI, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
...
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content=jsonable_encoder({"detail": exc.errors(), "Error": "Name field is missing"}),
)
...
@app.get("/")
async def hello(name: str):
return {"hello": name}
你会得到这样的回应:
$ curl 127.0.0.1:8000
{
"detail":[
{
"loc":[
"query",
"name"
],
"msg":"field required",
"type":"value_error.missing"
}
],
"Error":"Name field is missing"
}
content
但是,如果您愿意,您可以自定义:
{
"Error":"Name field is missing",
"Customize":{
"This":"content",
"Also you can":"make it simpler"
}
}