Defining an error handler for a particular exception

73 views
Skip to first unread message

Alberto

unread,
Feb 23, 2006, 8:29:33 AM2/23/06
to TurboGears
Hi,

I've just started playing with the new error handling mechanisms
recently introduced (which BTW look great :)

I have a, probably dumb, question:

How can I set a decorator for a method which redirects to another when
a particular exception occurs?

That is:

@error_handler(if exception is Y branch to method X)
def method:
# some code that could raise Y

def X:
# do something with the exception

I implicitly believed this could be done from skimming the
error_handling thread a couple of weeks ago but I can't seem to find
the post where (i believe) it said it or how to do it.

TIA,
Alberto

Alberto

unread,
Feb 23, 2006, 8:52:58 AM2/23/06
to TurboGears
Duh, shhould have read the errorhadling wiki before posting...

Ive managed to do it like:

class Root(controllers.RootController):
@turbogears.expose()
def error(self):
return "An error ocured"

@turbogears.expose()
@turbogears.controllers.exception_handler(error, "ValueError")
def index(self):
raise ValueError

BTW, Shouldn't exception_handler be imported at turbogears/__init__ too
like error_handler is, just for convenience...

Regards,
Alberto

Simon Belak

unread,
Feb 23, 2006, 10:02:03 AM2/23/06
to turbo...@googlegroups.com
Alberto wrote:
> Duh, shhould have read the errorhadling wiki before posting...
>
> Ive managed to do it like:
>
> class Root(controllers.RootController):
> @turbogears.expose()
> def error(self):
> return "An error ocured"
>
> @turbogears.expose()
> @turbogears.controllers.exception_handler(error, "ValueError")
> def index(self):
> raise ValueError

Are you sure, this works as expecetd?

Perhaps

"isinstance(tg_exceptions, ValueError)"

will serve you better.


> BTW, Shouldn't exception_handler be imported at turbogears/__init__ too
> like error_handler is, just for convenience...

Yes it should be (and is). Which version are you using?

Cheers,
Simon

Alberto

unread,
Feb 23, 2006, 10:26:08 AM2/23/06
to TurboGears
Actually I was just wondering why it didn't work as expected... :) It
first seemed so, but it was handling ALL exceptions... I'm going to try
your example...

Thanks for the help!

Alberto

P.S: Using r825, i've locally patched my turbogears/__init__.py with:
exception_handler = controllers.exception_handler
and works for me

Simon Belak

unread,
Feb 23, 2006, 10:38:46 AM2/23/06
to turbo...@googlegroups.com
Alberto wrote:
> P.S: Using r825, i've locally patched my turbogears/__init__.py with:
> exception_handler = controllers.exception_handler
> and works for me

I am such an idiot! Of curse, the line above is missing. Thanks!

Cheers,
Simon

Alberto

unread,
Feb 23, 2006, 10:39:13 AM2/23/06
to TurboGears
Works like a charm now... Thanks

P.S.

Are you sure it was imported?? I'm looking through the rev. log and
can't seem to find it...

Reply all
Reply to author
Forward
0 new messages