r/django • • 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?

5 Upvotes

18 comments sorted by

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:

error_logger("test")
try:
    external_api_route.get()
    error_logger("external API call success")
except Exception:
    error_logger("could not connect to external api")

2

u/Vietname 3d ago

Tried this already: neither of the logger calls in the try/except block get hit, just the test logger.

Might be worth noting that this code isn't in my view itself, but i have a view that calls it.

1

u/ninja_shaman 3d ago

So only "test" is logged, but "external API success" is not?

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/Vietname 3d ago

Im able to reproduce the error in a uv shell (also how I confirmed it was a ConnectionError), but it seems to behave differently when it's actually called in a view vs called directly. 

Also how come you call the route directly with .get()? The DRF library should do most boilerplate by itself 

Thats just there because it's psuedocode, im actually mounting the external api url in a requests Session and calling .get on that.

1

u/knuppi 3d ago

im actually mounting the external api url in a requests Session and calling .get on that.

ok, but that means that the problem is with requests, not with drf. or what am i misunderstanding?

1

u/Vietname 3d ago

I can catch the exception if i just run that code in a uv shell; i cant if it's in a DRF view. 

So it's not an issue with requests, seemingly.

1

u/knuppi 3d ago

Please paste the stack trace, it's difficult to understand what's happening

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/Vietname 3d ago

Nope, not using any kind of cache

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/Vietname 3d ago

I am indeed mounting an HTTPAdapter with a Retry, but i can run this code in a uv shell and get the ConnectionError. 

I am wondering if gunicorn's timeout is beating the HTTPAdapter's timeout though; thats a good point. Itd explain why i can reproduce this in a shell and get the stack trace, but not when i hit the actual view.

1

u/Vietname 2d ago

This ended up being the solution: i had the retry/backoff_factor too high and it got beat by the gunicorn timeout.

Thanks u/scraping_solutions!

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/bilcox 3d ago

If it's your actual server's 500 error and it's not raising, then it's handled in the layer you've pseudocoded here.

1

u/kapitansaluyot 3d ago

Maybe its actually a success? Try to see the response from that get request.