Skip to content

Commit 80c4ce6

Browse files
committed
重写HTTPException异常处理器 和 请求验证异常处理器
1 parent f6939c9 commit 80c4ce6

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

run.py

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,45 @@
44

55
import uvicorn
66
from fastapi import FastAPI
7+
from fastapi.exceptions import RequestValidationError
8+
from fastapi.responses import PlainTextResponse
9+
from starlette.exceptions import HTTPException as StarletteHTTPException
710

8-
from tutorial import app03
911
from coronavirus import application
12+
from tutorial import app03, app04
1013

1114
app = FastAPI(
1215
title='FastAPI Tutorial and Coronavirus Tracker API Docs',
13-
description='FastAPI教程和新冠病毒疫情跟踪器API接口文档,项目地址:https://github.com/liaogx/fastapi-tutorial',
16+
description='FastAPI教程 新冠病毒疫情跟踪器API接口文档,项目代码:https://github.com/liaogx/fastapi-tutorial',
1417
version='1.0.0',
1518
docs_url='/docs',
1619
redoc_url='/redocs',
1720
)
1821

19-
app.include_router(app03, prefix="/tutorial", tags=['Request请求'])
20-
app.include_router(application, prefix="/coronavirus", tags=['Coronavirus Tracker'])
22+
23+
# @app.exception_handler(StarletteHTTPException) # 重写HTTPException异常处理器
24+
# async def http_exception_handler(request, exc):
25+
# """
26+
# :param request: 这个参数不能省
27+
# :param exc:
28+
# :return:
29+
# """
30+
# return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
31+
#
32+
#
33+
# @app.exception_handler(RequestValidationError) # 重写请求验证异常处理器
34+
# async def validation_exception_handler(request, exc):
35+
# """
36+
# :param request: 这个参数不能省
37+
# :param exc:
38+
# :return:
39+
# """
40+
# return PlainTextResponse(str(exc), status_code=400)
41+
42+
43+
app.include_router(app03, prefix="/chapter03", tags=['第三章 请求参数和验证'])
44+
app.include_router(app04, prefix="/chapter04", tags=['第四章 响应处理和FastAPI配置'])
45+
app.include_router(application, prefix="/coronavirus", tags=['新冠病毒疫情跟踪器API'])
2146

2247
if __name__ == '__main__':
2348
uvicorn.run("run:app", host="0.0.0.0", port=8000, reload=True, debug=True, workers=1)

0 commit comments

Comments
 (0)