Skip to content

Commit 7d772b1

Browse files
committed
fix(main.py): Generate proper traceback on exception
Until now problems on API was very hard to debug due lack of proper traceback. Lets add it back. Signed-off-by: Denys Fedoryshchenko <denys.f@collabora.com>
1 parent 13b5152 commit 7d772b1

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

api/main.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import os
1212
import re
1313
import asyncio
14+
import traceback
1415
from typing import List, Union, Optional
1516
from datetime import datetime
1617
from contextlib import asynccontextmanager
@@ -1101,6 +1102,18 @@ async def get_metrics():
11011102
)
11021103

11031104

1105+
# traceback_exception_handler is a global exception handler that will be
1106+
# triggered for all exceptions that are not handled by specific exception
1107+
def traceback_exception_handler(request: Request, exc: Exception):
1108+
"""Global exception handler to print traceback"""
1109+
print(f"Exception: {exc}")
1110+
traceback.print_exception(type(exc), exc, exc.__traceback__)
1111+
return JSONResponse(
1112+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
1113+
content={"message": "Internal server error, check container logs"}
1114+
)
1115+
1116+
11041117
"""Workaround to use global exception handlers for versioned API.
11051118
The issue has already been reported here:
11061119
https://github.com/DeanWay/fastapi-versioning/issues/30
@@ -1113,6 +1126,10 @@ async def get_metrics():
11131126
sub_app.app.add_exception_handler(
11141127
errors.InvalidId, invalid_id_exception_handler
11151128
)
1129+
# print traceback for all other exceptions
1130+
sub_app.app.add_exception_handler(
1131+
Exception, traceback_exception_handler
1132+
)
11161133

11171134

11181135
@versioned_app.middleware("http")

0 commit comments

Comments
 (0)