Skip to content

Commit 33c9f78

Browse files
authored
Update the handling of CORS 500 status code (#789)
1 parent 37b1033 commit 33c9f78

File tree

2 files changed

+19
-73
lines changed

2 files changed

+19
-73
lines changed

backend/common/exception/exception_handler.py

Lines changed: 0 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
from fastapi.exceptions import RequestValidationError
55
from pydantic import ValidationError
66
from starlette.exceptions import HTTPException
7-
from starlette.middleware.cors import CORSMiddleware
87
from uvicorn.protocols.http.h11_impl import STATUS_PHRASES
98

109
from backend.common.exception.errors import BaseExceptionMixin
@@ -193,66 +192,8 @@ async def all_unknown_exception_handler(request: Request, exc: Exception):
193192
else:
194193
res = response_base.fail(res=CustomResponseCode.HTTP_500)
195194
content = res.model_dump()
196-
request.state.__request_all_unknown_exception__ = content
197195
content.update(trace_id=get_request_trace_id(request))
198196
return MsgSpecJSONResponse(
199197
status_code=StandardResponseCode.HTTP_500,
200198
content=content,
201199
)
202-
203-
if settings.MIDDLEWARE_CORS:
204-
205-
@app.exception_handler(StandardResponseCode.HTTP_500)
206-
async def cors_custom_code_500_exception_handler(request, exc):
207-
"""
208-
跨域自定义 500 异常处理
209-
210-
`Related issue <https://github.com/encode/starlette/issues/1175>`_
211-
212-
`Solution <https://github.com/fastapi/fastapi/discussions/7847#discussioncomment-5144709>`_
213-
214-
:param request: FastAPI 请求对象
215-
:param exc: 自定义异常
216-
:return:
217-
"""
218-
if isinstance(exc, BaseExceptionMixin):
219-
content = {
220-
'code': exc.code,
221-
'msg': exc.msg,
222-
'data': exc.data,
223-
}
224-
else:
225-
if settings.ENVIRONMENT == 'dev':
226-
content = {
227-
'code': StandardResponseCode.HTTP_500,
228-
'msg': str(exc),
229-
'data': None,
230-
}
231-
else:
232-
res = response_base.fail(res=CustomResponseCode.HTTP_500)
233-
content = res.model_dump()
234-
request.state.__request_cors_500_exception__ = content
235-
content.update(trace_id=get_request_trace_id(request))
236-
response = MsgSpecJSONResponse(
237-
status_code=exc.code if isinstance(exc, BaseExceptionMixin) else StandardResponseCode.HTTP_500,
238-
content=content,
239-
background=exc.background if isinstance(exc, BaseExceptionMixin) else None,
240-
)
241-
origin = request.headers.get('origin')
242-
if origin:
243-
cors = CORSMiddleware(
244-
app=app,
245-
allow_origins=settings.CORS_ALLOWED_ORIGINS,
246-
allow_credentials=True,
247-
allow_methods=['*'],
248-
allow_headers=['*'],
249-
expose_headers=settings.CORS_EXPOSE_HEADERS,
250-
)
251-
response.headers.update(cors.simple_headers)
252-
has_cookie = 'cookie' in request.headers
253-
if cors.allow_all_origins and has_cookie:
254-
response.headers['Access-Control-Allow-Origin'] = origin
255-
elif not cors.allow_all_origins and cors.is_allowed_origin(origin=origin):
256-
response.headers['Access-Control-Allow-Origin'] = origin
257-
response.headers.add_vary_header('Origin')
258-
return response

backend/core/registrar.py

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@
1313
from fastapi_limiter import FastAPILimiter
1414
from fastapi_pagination import add_pagination
1515
from starlette.middleware.authentication import AuthenticationMiddleware
16+
from starlette.middleware.cors import CORSMiddleware
1617
from starlette.staticfiles import StaticFiles
18+
from starlette.types import ASGIApp
1719

1820
from backend.common.exception.exception_handler import register_exception
1921
from backend.common.log import set_custom_logfile, setup_logging
@@ -65,7 +67,23 @@ async def register_init(app: FastAPI) -> AsyncGenerator[None, None]:
6567

6668
def register_app() -> FastAPI:
6769
"""注册 FastAPI 应用"""
68-
app = FastAPI(
70+
71+
class MyFastAPI(FastAPI):
72+
if settings.MIDDLEWARE_CORS:
73+
# Related issues
74+
# https://github.com/fastapi/fastapi/discussions/7847
75+
# https://github.com/fastapi/fastapi/discussions/8027
76+
def build_middleware_stack(self) -> ASGIApp:
77+
return CORSMiddleware(
78+
super().build_middleware_stack(),
79+
allow_origins=settings.CORS_ALLOWED_ORIGINS,
80+
allow_credentials=True,
81+
allow_methods=['*'],
82+
allow_headers=['*'],
83+
expose_headers=settings.CORS_EXPOSE_HEADERS,
84+
)
85+
86+
app = MyFastAPI(
6987
title=settings.FASTAPI_TITLE,
7088
version=settings.FASTAPI_VERSION,
7189
description=settings.FASTAPI_DESCRIPTION,
@@ -134,19 +152,6 @@ def register_middleware(app: FastAPI) -> None:
134152
# I18n
135153
app.add_middleware(I18nMiddleware)
136154

137-
# CORS
138-
if settings.MIDDLEWARE_CORS:
139-
from fastapi.middleware.cors import CORSMiddleware
140-
141-
app.add_middleware(
142-
CORSMiddleware,
143-
allow_origins=settings.CORS_ALLOWED_ORIGINS,
144-
allow_credentials=True,
145-
allow_methods=['*'],
146-
allow_headers=['*'],
147-
expose_headers=settings.CORS_EXPOSE_HEADERS,
148-
)
149-
150155
# Access log
151156
app.add_middleware(AccessMiddleware)
152157

0 commit comments

Comments
 (0)