如何在 FastAPI 中自定义特定路由的错误响应?
自定义 FastAPI 中特定路由的错误响应
概述
FastAPI [1](#sources) 提供了 多功能平台针对自定义错误针对特定路线的回复。这允许开发人员根据特定的应用程序要求定制错误处理。通过覆盖默认异常处理程序或采用子应用程序等其他技术,可以创建自定义错误响应,增强用户体验并提供有意义的反馈。
选项 1:覆盖默认异常处理程序
一种方法涉及覆盖 RequestValidationError 的默认异常处理程序。当请求包含无效数据时会引发此异常。通过实现自定义处理程序,您可以检查与所需的自定义标头相关的特定错误,并返回自定义错误响应。
from fastapi import FastAPI, Request, Header, status from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from fastapi.encoders import jsonable_encoder app = FastAPI() routes_with_custom_exception = ['/'] @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): if request.url.path in routes_with_custom_exception: # check whether the error relates to the `some_custom_header` parameter for err in exc.errors(): if err['loc'][0] == 'header' and err['loc'][1] == 'some-custom-header': return JSONResponse(content={'401': 'Unauthorized'}, status_code=401) return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content=jsonable_encoder({'detail': exc.errors(), 'body': exc.body}), )
选项 2:子-应用程序
另一种选择涉及创建子应用程序和安装它们到主应用程序。这允许特定于子应用程序内的路由的自定义错误处理,而不影响主应用程序中的其他路由。
# main API app = FastAPI() # sub-application with custom error handling subapi = FastAPI() @subapi.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): # Handle error specific to sub-application's routes return JSONResponse(content={'401': 'Unauthorized'}, status_code=401) # mount sub-application app.mount('/sub', subapi)
选项 3:自定义 APIRoute 类
此方法涉及创建一个自定义 APIRoute 类,用于在 try- except 块中处理请求验证。如果引发 RequestValidationError,则可以返回自定义错误响应。
from fastapi import FastAPI, APIRouter, APIRoute, Request, Header, HTTPException from fastapi.responses import JSONResponse from fastapi.exceptions import RequestValidationError class ValidationErrorHandlingRoute(APIRoute): def get_route_handler(self) -> Callable: original_route_handler = super().get_route_handler() async def custom_route_handler(request: Request) -> Response: try: return await original_route_handler(request) except RequestValidationError as e: raise HTTPException(status_code=401, detail='401 Unauthorized') # create new router with custom error handling router = APIRouter(route_class=ValidationErrorHandlingRoute) # add custom error handling to router @router.get('/custom') async def custom_route(some_custom_header: str = Header(...)): return {'some-custom-header': some_custom_header} # add router to app app.include_router(router)
结论
通过探索这些技术,开发人员可以在 FastAPI 中自定义错误响应以满足特定要求,从而提供更多定制的用户体验和增强的错误处理能力。
来源
- [FastAPI 文档:处理 HTTP 异常](https://fastapi.tiangolo.com/exception-handlers/)
以上是如何在 FastAPI 中自定义特定路由的错误响应?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...

Python3.6环境下加载pickle文件报错:ModuleNotFoundError:Nomodulenamed...

使用Scapy爬虫时管道文件无法写入的原因探讨在学习和使用Scapy爬虫进行数据持久化存储时,可能会遇到管道文�...
