FastAPI中怎么实现API错误处理

avatar
作者
猴君
阅读量:0

在FastAPI中,可以使用HTTPException类来实现API错误处理。通过抛出HTTPException异常,可以返回自定义的HTTP状态码和错误信息。

示例代码如下:

from fastapi import FastAPI, HTTPException  app = FastAPI()  @app.get("/items/{item_id}") def read_item(item_id: int):     if item_id == 0:         raise HTTPException(status_code=404, detail="Item not found")     return {"item_id": item_id} 

在上面的例子中,如果传入的item_id为0,就会抛出一个404错误,返回"Item not found"的错误信息。

除了使用HTTPException类外,还可以通过异常处理器来处理API错误。示例代码如下:

from fastapi import FastAPI, HTTPException from fastapi.responses import JSONResponse  app = FastAPI()  @app.exception_handler(HTTPException) async def http_exception_handler(request, exc):     return JSONResponse(         status_code=exc.status_code,         content={"detail": exc.detail}     )  @app.get("/items/{item_id}") def read_item(item_id: int):     if item_id == 0:         raise HTTPException(status_code=404, detail="Item not found")     return {"item_id": item_id} 

在上面的例子中,定义了一个异常处理器http_exception_handler,用来处理HTTPException异常。当抛出HTTPException异常时,会调用http_exception_handler处理器来返回自定义的错误信息。

通过以上两种方法,可以实现API错误处理并返回自定义的错误信息。