From 9a955f4739a46d46848122ceda188020221a6aac Mon Sep 17 00:00:00 2001 From: Denys Fedoryshchenko Date: Thu, 12 Dec 2024 20:30:16 +0200 Subject: [PATCH 1/2] 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 --- api/main.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/api/main.py b/api/main.py index 8d6c2d63..5db28950 100644 --- a/api/main.py +++ b/api/main.py @@ -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 @@ -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 @@ -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") From 571c64d240b8585481977c2a255b18faffddec2f Mon Sep 17 00:00:00 2001 From: Denys Fedoryshchenko Date: Thu, 12 Dec 2024 20:44:34 +0200 Subject: [PATCH 2/2] fix(main.py): Fix pylint warning Signed-off-by: Denys Fedoryshchenko --- api/main.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/api/main.py b/api/main.py index 5db28950..a664dedb 100644 --- a/api/main.py +++ b/api/main.py @@ -1114,10 +1114,9 @@ def traceback_exception_handler(request: Request, exc: Exception): ) -"""Workaround to use global exception handlers for versioned API. -The issue has already been reported here: -https://github.com/DeanWay/fastapi-versioning/issues/30 -""" +# Workaround to use global exception handlers for versioned API. +# The issue has already been reported here: +# https://github.com/DeanWay/fastapi-versioning/issues/30 for sub_app in versioned_app.routes: if hasattr(sub_app.app, "add_exception_handler"): sub_app.app.add_exception_handler(