Issue
I've got a function a() that calls other functions b() , c() and d() this way (I schematize):
a()
def a(request):
try:
b(request)
except Exception:
messages.error(request, 'error')
try:
c(request)
except Exception:
messages.error(request, 'error')
try:
d(request)
except Exception:
messages.error(request, 'error')
return redirect('namespace:url_name')
b()
def b(request):
try:
do_something()
messages.success(request, 'I did')
except Exception:
messages.error(request, 'Couldn\'t do the thing')
return redirect('namespace:url_name')
But if an exception triggers in b() , its redirection doesn't work and c() and d() are still executed in a().
Did I miss something in my redirect or exception handling comprehension ? Because even if I set a redirect in all a functions' Exceptions, the behavior doesn't change.
Solution
You don't return the result of b
in a
, so, regardless what b
returns, it will still process c
, and d
. The return redirect
will return, but it will return out of b
, it does not return out of the callers of b
, that doe snot make much sense.
We thus should check if b
returns something, if that is the case, return the result, otherwise continue:
def a(request):
try:
result = b(request)
if result is not None:
return result
except Exception:
messages.error(request, 'error')
try:
result = c(request)
if result is not None:
return result
except Exception:
messages.error(request, 'error')
try:
result = d(request)
if result is not None:
return result
except Exception:
messages.error(request, 'error')
return redirect('namespace:url_name')
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.