Skip to content

Commit

Permalink
fix(main.py): Generate proper traceback on exception
Browse files Browse the repository at this point in the history
Until now problems on API was very hard to debug due lack
of proper traceback. Lets add it back.

Signed-off-by: Denys Fedoryshchenko <[email protected]>
  • Loading branch information
nuclearcat committed Dec 12, 2024
1 parent 13b5152 commit 7d772b1
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import os
import re
import asyncio
import traceback
from typing import List, Union, Optional
from datetime import datetime
from contextlib import asynccontextmanager
Expand Down Expand Up @@ -1101,6 +1102,18 @@ async def get_metrics():
)


# traceback_exception_handler is a global exception handler that will be
# triggered for all exceptions that are not handled by specific exception
def traceback_exception_handler(request: Request, exc: Exception):
"""Global exception handler to print traceback"""
print(f"Exception: {exc}")
traceback.print_exception(type(exc), exc, exc.__traceback__)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"message": "Internal server error, check container logs"}
)


"""Workaround to use global exception handlers for versioned API.
The issue has already been reported here:
https://github.com/DeanWay/fastapi-versioning/issues/30
Expand All @@ -1113,6 +1126,10 @@ async def get_metrics():
sub_app.app.add_exception_handler(
errors.InvalidId, invalid_id_exception_handler
)
# print traceback for all other exceptions
sub_app.app.add_exception_handler(
Exception, traceback_exception_handler
)


@versioned_app.middleware("http")
Expand Down

0 comments on commit 7d772b1

Please sign in to comment.