python系列:FASTAPI系列 19返回异常处理 & FASTAPI系列 20-异常处理器exception_handler

331 篇文章 ¥99.90 ¥299.90




一、 FASTAPI系列 19返回异常处理

前言

某些情况下,需要向客户端返回错误提示。这里所谓的客户端包括前端浏览器、其他应用程序、物联网设备等。需要向客户端返回错误提示的场景主要如下:

  • 遇到这些情况时,通常要返回 4XX(400 至 499)HTTP 状态码。

  • 4XX 状态码与表示请求成功的 2XX(200 至 299) HTTP 状态码类似。只不过,4XX 状态码表示客户端发生的错误。

一、使用 HTTPException

向客户端返回 HTTP 错误响应,可以使用 HTTPException

from fastapi import FastAPI, HTTPException

app = FastAPI(
FO: Will watch for changes in these directories: ['E:\\python\\Python313\\fastapi\\ORM系统'] INFO: Uvicorn running on http://127.0.0.1:8080 (Press CTRL+C to quit) INFO: Started reloader process [8364] using StatReload INFO: Started server process [12812] INFO: Waiting for application startup. INFO: Application startup complete. INFO: 127.0.0.1:63944 - "GET /docs HTTP/1.1" 200 OK INFO: 127.0.0.1:63944 - "GET /openapi.json HTTP/1.1" 200 OK INFO: 127.0.0.1:63944 - "GET /student/ HTTP/1.1" 500 Internal Server Error ERROR: Exception in ASGI application Traceback (most recent call last): File "E:\python\Python313\fastapi\.venv\Lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 403, in run_asgi result = await app( # type: ignore[func-returns-value] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ self.scope, self.receive, self.send ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ) ^ File "E:\python\Python313\fastapi\.venv\Lib\site-packages\uvicorn\middleware\proxy_headers.py", line 60, in __call__ return await self.app(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Python313\fastapi\.venv\Lib\site-packages\fastapi\applications.py", line 1054, in __call__ await super().__call__(scope, receive, send) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\applications.py", line 112, in __call__ await self.middleware_stack(scope, receive, send) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\middleware\errors.py", line 187, in __call__ raise exc File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\middleware\errors.py", line 165, in __call__ await self.app(scope, receive, _send) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\middleware\exceptions.py", line 62, in __call__ await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\_exception_handler.py", line 53, in wrapped_app raise exc File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\_exception_handler.py", line 42, in wrapped_app await app(scope, receive, sender) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\routing.py", line 714, in __call__ await self.middleware_stack(scope, receive, send) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\routing.py", line 734, in app await route.handle(scope, receive, send) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\routing.py", line 288, in handle await self.app(scope, receive, send) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\routing.py", line 76, in app await wrap_app_handling_exceptions(app, request)(scope, receive, send) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\_exception_handler.py", line 53, in wrapped_app raise exc File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\_exception_handler.py", line 42, in wrapped_app await app(scope, receive, sender) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\starlette\routing.py", line 73, in app response = await f(request) ^^^^^^^^^^^^^^^^ File "E:\python\Python313\fastapi\.venv\Lib\site-packages\fastapi\routing.py", line 301, in app raw_response = await run_endpoint_function( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<3 lines>... ) ^ File "E:\python\Python313\fastapi\.venv\Lib\site-packages\fastapi\routing.py", line 212, in run_endpoint_function return await dependant.call(**values) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\python\Python313\fastapi\ORM系统\api\students.py", line 26, in get_all_students stu1 = await Students.filter(sno__gt=2003) ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^ File "E:\python\Python313\fastapi\.venv\Lib\site-packages\tortoise\models.py", line 1323, in filter return cls._meta.manager.get_queryset().filter(*args, **kwargs) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^ File "E:\python\Python313\fastapi\.venv\Lib\site-packages\tortoise\manager.py", line 19, in get_queryset return QuerySet(self._model) File "E:\python\Python313\fastapi\.venv\Lib\site-packages\tortoise\queryset.py", line 337, in __init__ super().__init__(model) ~~~~~~~~~~~~~~~~^^^^^^^ File "E:\python\Python313\fastapi\.venv\Lib\site-packages\tortoise\queryset.py", line 99, in __init__ self.capabilities: Capabilities = model._meta.db.capabilities ^^^^^^^^^^^^^^ File "E:\python\Python313\fastapi\.venv\Lib\site-packages\tortoise\models.py", line 280, in db raise ConfigurationError( f"default_connection for the model {self._model} cannot be None" ) tortoise.exceptions.ConfigurationError: default_connection for the model <class 'ORM系统.models.Students'> cannot be None
最新发布
06-30
FastAPI 应用中添加自定义异常处理器可以通过 `@app.exception_handler()` 装饰器实现,这一机制允许开发者捕获特定的异常返回定制化的响应。例如,可以为 `HTTPException` 添加一个全局处理器,以统一处理所有由应用抛出的 HTTP 错误。 以下是一个示例,展示如何添加一个自定义异常处理器来捕获和处理 `HTTPException`: ```python from fastapi import FastAPI, HTTPException from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(HTTPException) async def http_exception_handler(request, exc): # 返回一个自定义的 JSON 响应,包含状态码和错误信息 return JSONResponse( status_code=exc.status_code, content={"error": exc.detail}, ) @app.get("/example") async def example_endpoint(): # 抛出一个 HTTP 异常 raise HTTPException(status_code=400, detail="Bad request") ``` 上述代码中,当 `/example` 端点被调用时,会抛出一个 `HTTPException`,其状态码为 400,错误信息为 "Bad request"。由于已经定义了针对 `HTTPException` 的异常处理器,该异常会被捕获,并通过 `JSONResponse` 返回一个格式化的 JSON 响应[^1]。 此外,还可以为非 HTTP 特定的异常(如自定义异常类)添加处理器。例如,定义一个名为 `CustomError` 的异常类,并为其添加一个处理器: ```python class CustomError(Exception): pass @app.exception_handler(CustomError) async def custom_error_handler(request, exc): return JSONResponse( status_code=500, content={"error": "Internal server error"}, ) @app.get("/custom-example") async def custom_example_endpoint(): # 抛出自定义异常 raise CustomError() ``` 在这个例子中,当 `/custom-example` 端点被调用时,会抛出一个 `CustomError` 异常。该异常会被 `custom_error_handler` 捕获,并返回一个状态码为 500 的 JSON 响应,内容为 "Internal server error"[^1]。 这种机制不仅提升了错误处理的一致性,还增强了用户体验,因为客户端可以接收到结构化且有意义的错误信息。 ### 相关问题 1. 如何在 FastAPI 中使用中间件进行请求拦截和处理? 2. 如何在 FastAPI 中实现 JWT 身份验证? 3. 如何限制 FastAPI 应用中的并发请求数量? 4. 如何在 FastAPI 中记录日志以便调试异常
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

坦笑&&life

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值