推荐答案
在 FastAPI 中,错误处理主要通过 HTTPException 和自定义异常处理器来实现。以下是推荐的错误处理方式:
使用 HTTPException
HTTPException 是 FastAPI 提供的一个内置异常类,用于处理 HTTP 请求中的错误。你可以通过抛出 HTTPException 来返回特定的 HTTP 状态码和错误信息。
// www.javascriptcn.com code example
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id == 42:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id}自定义异常处理器
如果你需要处理特定的异常类型,可以使用 @app.exception_handler 来注册自定义的异常处理器。
// www.javascriptcn.com code example
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
app = FastAPI()
class CustomException(Exception):
def __init__(self, name: str):
self.name = name
@app.exception_handler(CustomException)
async def custom_exception_handler(request: Request, exc: CustomException):
return JSONResponse(
status_code=418,
content={"message": f"Oops! {exc.name} did something wrong."},
)
@app.get("/custom-exception")
async def raise_custom_exception():
raise CustomException(name="John")本题详细解读
HTTPException 的使用
HTTPException 是 FastAPI 中最常用的错误处理方式。它允许你在代码中抛出异常,并指定 HTTP 状态码和错误信息。FastAPI 会自动捕获这些异常,并将其转换为对应的 HTTP 响应。
status_code: 指定 HTTP 状态码,如 404(未找到)、400(错误请求)等。detail: 提供错误的详细信息,通常是一个字符串。
自定义异常处理器
自定义异常处理器允许你处理特定的异常类型,并返回自定义的响应。通过 @app.exception_handler 装饰器,你可以为特定的异常类型注册处理器。
CustomException: 自定义的异常类,继承自Exception。custom_exception_handler: 自定义的异常处理器函数,接收Request对象和异常实例作为参数,返回一个JSONResponse或其他响应类型。
其他错误处理方式
除了上述两种方式,FastAPI 还支持通过中间件、依赖注入等方式进行错误处理。你可以根据具体需求选择合适的方式。
示例代码
以下是一个完整的示例,展示了如何在 FastAPI 中使用 HTTPException 和自定义异常处理器:
// www.javascriptcn.com code example
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
app = FastAPI()
class CustomException(Exception):
def __init__(self, name: str):
self.name = name
@app.exception_handler(CustomException)
async def custom_exception_handler(request: Request, exc: CustomException):
return JSONResponse(
status_code=418,
content={"message": f"Oops! {exc.name} did something wrong."},
)
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id == 42:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id}
@app.get("/custom-exception")
async def raise_custom_exception():
raise CustomException(name="John")在这个示例中,访问 /items/42 会返回 404 错误,而访问 /custom-exception 会触发自定义异常处理器,返回 418 状态码和自定义的错误信息。