24 FastAPI错误处理之HTTP异常响应

在上一篇中,我们讨论了如何在FastAPI中实现自定义异常处理。在这一篇中,我们将继续错误处理的主题,重点介绍如何返回HTTP异常响应,以及如何利用FastAPI内置的异常处理机制,提高应用程序的健壮性。

1. HTTP异常响应的介绍

在FastAPI中,HTTP异常响应用于指示请求中发生的错误,并返回合适的HTTP状态码和错误信息。通常情况下,我们会利用HTTPException类来处理常见的错误情况,例如请求的资源未找到、权限不足等。

1.1 使用HTTPException

HTTPException是FastAPI内置的异常类,它允许我们抛出HTTP错误。在发生异常时,FastAPI会自动异常捕获,并返回相应的HTTP响应。

1
2
3
4
5
6
7
8
9
10
11
12
from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id < 0:
raise HTTPException(status_code=400, detail="Item ID must be a positive integer")
if item_id > 10:
raise HTTPException(status_code=404, detail="Item not found")

return {"item_id": item_id, "name": f"Item {item_id}"}

在这个例子中,我们定义了一个获取商品信息的接口/items/{item_id}。如果item_id小于0,则抛出400状态码的异常,说明请求参数不合法;如果item_id大于10,则抛出404状态码的异常,表示没有找到对应的商品。

2. 自定义错误响应

虽然可以使用HTTPException生成简单的错误响应,但有时我们需要提供更详细的错误信息。这时候,可以通过继承HTTPException,来自定义我们的错误响应结构。

2.1 自定义异常类

创建一个自定义异常类时,我们可以添加更多上下文信息,来帮助用户理解错误的原因。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

class CustomHTTPException(HTTPException):
def __init__(self, status_code: int, detail: str, errors: list = None):
super().__init__(status_code=status_code, detail=detail)
self.errors = errors or []

app = FastAPI()

@app.post("/items/")
async def create_item(item: BaseModel):
if "name" not in item.dict():
raise CustomHTTPException(
status_code=422,
detail="Validation Error",
errors=["'name' is required"]
)
return {"item": item}

在这个例子中,我们定义了一个CustomHTTPException,它允许我们传递额外的错误信息。在create_item接口中,如果请求的数据不包含name字段,则返回422状态码及相应的错误信息。

3. 快速错误响应的统一处理

为了避免在每个路由处理函数中手动抛出异常,我们可以创建一个全局错误处理器。这样可以集中管理错误响应,提高代码的可维护性。

3.1 设置全局异常处理器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from fastapi import FastAPI, Request

app = FastAPI()

@app.exception_handler(CustomHTTPException)
async def custom_http_exception_handler(request: Request, exc: CustomHTTPException):
return JSONResponse(
status_code=exc.status_code,
content={"message": exc.detail, "errors": exc.errors},
)

@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id < 0:
raise CustomHTTPException(status_code=400, detail="Item ID must be a positive integer")
if item_id > 10:
raise CustomHTTPException(status_code=404, detail="Item not found")

return {"item_id": item_id, "name": f"Item {item_id}"}

在这个示例中,我们使用@app.exception_handler()装饰器注册了一个全局HTTP异常处理器。所有抛出的CustomHTTPException都会被该处理器捕获,返回统一格式的JSON响应。

4. 总结

在本文中,我们介绍了FastAPI中如何使用HTTPException来处理HTTP异常响应,并探讨了如何通过自定义异常类及全局异常处理器来改善错误应对机制。这使得错误处理更加灵活和可控,为API的使用者提供了更友好的错误信息。

在下一篇,我们将深入探讨中间件与依赖注入的概念与使用,帮助你构建更复杂的FastAPI应用。希望本篇能为你在项目中的错误处理提供参考和帮助!

24 FastAPI错误处理之HTTP异常响应

https://zglg.work/python-fastapi-zero/24/

作者

IT教程网(郭震)

发布于

2024-08-17

更新于

2024-08-18

许可协议

分享转发

交流

更多教程加公众号

更多教程加公众号

加入星球获取PDF

加入星球获取PDF

打卡评论