how should i handle redirects within try/except statements ?

3 views
Skip to first unread message

Jonathan Vanasco

unread,
Oct 12, 2009, 11:33:15 PM10/12/09
to pylons-discuss
i have some code that looks like this:

class controller:
def index(self):
"""dispatcher""
try:
dbsetup()
authorize_this_task()
if action == 'a':
self.other_action()
...etc...
except:
error()

def other_action(self):
try:
do_another_thing()
dbcommit()
except:
handle_error()
raise
redirect(success_url)

the issue is that redirect() raises a "webob.exc" error, which means
my code get really really messy trying to catch it.

right now some methods that are dispatched to redirect, others return
a render

a lot of this was coded before i realized how redirect worked. i would
have done things differently had i realized this all.

anyone have a suggestion on how i can handle this better?

Piotr Kęplicz

unread,
Oct 13, 2009, 3:19:22 AM10/13/09
to pylons-...@googlegroups.com
Jonathan Vanasco, wtorek 13 października 2009 05:33:
[...]

> the issue is that redirect() raises a "webob.exc" error, which means
> my code get really really messy trying to catch it.

Catch and re-raise HTTPRedirections.

from webob.exc import HTTPRedirection

try:
stuff()
except HTTPRedirection:
raise
except e: # other exceptions
handle_error(e)

.pk.

Jonathan Vanasco

unread,
Oct 14, 2009, 12:36:42 PM10/14/09
to pylons-discuss
Thanks! That's exactly it!

Where did you learn this?

I couldn't figure out what the error was. A trace showed HTTPFound,
but that didn't seem right. It catches, but HTTPRedirect catches the
same thing and seems more correct.

Mike Orr

unread,
Oct 14, 2009, 2:54:44 PM10/14/09
to pylons-...@googlegroups.com

HTTPFound (302) is a subclass of HTTPRedirect (300-399), which in turn
is a subclass of HTTPException (100-599). So the "proper" thing to do
is to catch and re-raise HTTPException.

This is not very intuitive or documented. I never encountered it
because I call redirect() and abort() only in the actions themselves.
I can't think of any way to improve it without changing the paradigm,
and exceptions are uniquely suited to this task of jumping back
through the call stack to some unknown handler. So I guess we'll just
have to put a note in the manual.

--
Mike Orr <slugg...@gmail.com>

Piotr Kęplicz

unread,
Oct 14, 2009, 3:07:05 PM10/14/09
to pylons-...@googlegroups.com, Jonathan Vanasco
Jonathan Vanasco, środa 14 października 2009 18:36:

> Thanks! That's exactly it!
>
> Where did you learn this?

I must have caught it in my code - once or twice ;-)

.pk.

Reply all
Reply to author
Forward
0 new messages