When the decision was made to use an Exception for redirecting, it was
for a good one due to the internal design of CherryPy. This is likely to
change from CP3 (which is not yet clearly designed yet so it will take
several months).
IMO, the controlle should not raise an exception but simply return any
value it requires and let the page handler decide what to do with it.
Only page handlers should deal with CherryPy code (I'm saying that but
note that I don't know very well what DataController does apart from
creating an object).
A workaround could be to specify which particular Exception you want to
to catch instead of broadly catch everything with Exception. So that you
would not catch CherryPy exceptions.
Then again, I believe you want to catch Errors not Exceptions. Errors
happen when something breaks. Exception are by designed allowed but
should happen because the developer has decided it. A redirect is
something one is intentional about in a web application and is therefore
an Exception. A problem that would occur when creating an object is an
Error by itself. The semantic is similar but if it was the same, both
would not exist.
- Sylvain
Simon Belak a écrit :
Randall wrote:
I ran into this interesting issue. I have a method that looks like
this:
def create(self, reviewer, writer, permission, tg_errors=None):
if tg_errors:
turbogears.flash(str(tg_errors))
return self.add())
try:
data = dict(reviewer=reviewer, writer=writer,
permission=permission)
DataController.create(self, **data)
except Exception, e:
self.sql_class._connection.rollback()
turbogears.flash(e)
return self.add()
When DataController.create finishes, it issues a cherrypy.HTTPRedirect,
which my try block catches and treats like a "bad" Exception. My
personal take on this is that redirecting via Exception is a bad thing
because I can't assume an Exception is something I don't want. I know
I could work around it by checking for particular Exceptions or using a
decorator, but I still think this is a bad thing. It should just be
cherrypy.redirect. Unfortunately, turbogears.redirect raises
cherrypy.HTTPRedirect.
Randall
+1
I don't like explicit redirects period. The way CP works I really don't
see any use-case for redirects within scope visible to the controller.
REST-full URLs, sure, but that shouldn't dictate programming decisions.
Simon