r/django • u/Vietname • 3d ago
REST framework Cant capture 500 error from external api in try/except block
In my DRF app im trying to capture 500 errors from an external api we hit so i can log them appropriately. Pseudo code:
error_logger("test")
try:
external_api_route.get()
except Exception:
error_logger("could not connect to external api")
The first logger call logs the test message just fine, but i cant get the second to do any logging.
The actual error is a requests.exceptions.ConnectionError, but i used a broad Exception just to make sure i wasnt missing anything while debugging.
Originally the error was happening on startup (hence why i was able to see the ConnectionError), but i refactored the code so an external api error doesnt bring down my entire app. But since doing so im unable to see the stack trace in any of my logging.
Is something in DRF/django intercepting these 500 errors from the external api? And if so how can i intercept them back?
2
u/ninja_shaman 3d ago
Django only handles exceptions that your view didn't handle.
Try this code to see if
external_api_route.get()actually raised an exception:1
u/Vietname 2d ago
u/scraping_solutions came up with the answer: gunicorn was timing out. See their comment below for the full explanation.
1
u/old-and-very-bald 3d ago
I would recommend to set a breakpoint to use the debugger. Then you can step through the Code and find exactly the spot you are looking for.
Also how come you call the route directly with .get()?
The DRF library should do most boilerplate by itself
1
u/Jejerm 3d ago
Are you using any type of cache and maybe its cacheing the error on first try and them doesnt even run it at all after that?
1
u/scraping_solutions 3d ago
If neither line after the call logs, the call probably never returns or raises at all, rather than Django swallowing an exception. requests has no default timeout, so a Session.get can hang for a very long time, and if you mounted an HTTPAdapter with a Retry that has many retries and a backoff_factor, the ConnectionError can take a long time to show up. Pass an explicit timeout, for example timeout=(3, 10), and see whether the except branch starts logging. Also check whether your server kills the worker on a timeout (gunicorn does this after 30 seconds by default), since that would also explain why nothing after the call is ever logged. Inside the except, logger.exception(...) will include the traceback for you.
1
u/bilcox 3d ago
Then you aren't getting an Exception, but an error response. Capture the response in a variable and read the status code and message.
1
u/kapitansaluyot 3d ago
Maybe its actually a success? Try to see the response from that get request.