python - re-raise exception from method as argument -
i have method needs wrapping called joule, wrap joule
method inside wrapper called respond
(which see shortly):
someclass.respond(somemodule.joule(someargument, somestrategy), 202)
i have wrapper called respond
:
@classmethod def respond(cls, method, successstatus): try: method, successstatus except exception e: return { 'status': 500, 'message': str(e) }
the actual method gets called , raises exception
:
def joule(params, strategy): try: return strategy(params) finally: session.rollback() conn.execute('unlock tables')
for reason, re-raised exception not seem caught in respond wrapper! can folks me understand doing incorrectly here?
if helps, exception being thrown sqlalchemy (please note scenario being forcibly created handle exception correctly):
programmingerror: (programmingerror) (1146, u"table 'matrix.vmop_queue' doesn't exist") 'lock tables vmop_queue write' ()
you misunderstanding how exception handling works. exception handling operates on stack frame of called functions.
in example give, someclass.respond
not invoke somemodule.joule
, instead wherever line have written in example, outer context place receives uncaught exception. someclass.respond
can't possibly handle exception thrown somemodule.joule
.
there other ways achieve trying accomplish, need more context in order give better suggestion.
to make bit more concrete, let's foo
contains example line gave:
def foo(): someclass.respond(somemodule.joule(someargument, somestrategy), 202)
you add try
block foo
handle exception thrown somemodule.joule
. this:
def foo(): try: someclass.respond(somemodule.joule(someargument, somestrategy), 202) except exception e: pass # exception here
alternatively, if whole purpose someclass.respond
handle exception, should move invocation of somemodule.joule
inside of someclass.respond
. more 1 way. generically take function , arguments, , apply function arguments inside of someclass.respond
or directly invocation inside of someclass.respond
.
let's take first approach, since you've said don't want repeat exception handling. i'll call new method exception_catcher
:
def exception_catcher(func, *args): try: return func(*args) except exception e: pass # whatever want exception
now foo
context this:
def foo(): exception_catcher(somemodule.joule, someargument, somestrategy)
note exception_catcher
taking somemodule.joule
argument, , remaining arguments passed somemodule.joule
within exception_catcher
.
Comments
Post a Comment