[英]re-raise exception from method as argument
我有一个需要包装的方法,称为焦耳,因此我将joule
方法包装在一个名为respond
的包装器中(稍后将看到):
someclass.respond(somemodule.joule(someArgument, someStrategy), 202)
我有一个包装叫做respond
:
@classmethod
def respond(cls, method, successStatus):
try:
method, successStatus
except Exception as e:
return {
'status': 500,
'message': str(e)
}
被调用并引发Exception
的实际方法:
def joule(params, strategy):
try:
return strategy(params)
finally:
session.rollback()
conn.execute('UNLOCK TABLES')
由于某种原因,重新引发的异常似乎没有被响应包装捕获! 你们可以帮我了解我在这里做错了什么吗?
如果这有帮助,则由sqlalchemy抛出异常(请注意,这是为了强制正确处理此异常而创建的方案):
ProgrammingError: (ProgrammingError) (1146, u"Table 'matrix.vmop_queue' doesn't exist") 'LOCK TABLES vmop_queue WRITE' ()
您误解了异常处理的工作原理。 异常处理在被调用函数的堆栈框架上进行。
在您给出的示例中, someclass.respond
实际上并不会调用somemodule.joule
,而是在示例中您所写的行中的任何外部上下文中都将接收未捕获的异常。 因此someclass.respond
可能无法处理somemodule.joule
引发的somemodule.joule
。
还有其他方法可以实现您要实现的目标,但是我需要更多的上下文信息才能为您提供更好的建议。
为了更具体一点,假设foo
包含您提供的示例行:
def foo():
someclass.respond(somemodule.joule(someArgument, someStrategy), 202)
您可以在foo
添加try
块,以处理somemodule.joule
引发的somemodule.joule
。 看起来像这样:
def foo():
try:
someclass.respond(somemodule.joule(someArgument, someStrategy), 202)
except Exception as e:
pass # do something with the exception here
另外,如果整个目的someclass.respond
是处理这个异常,那么你应该移动的调用somemodule.joule
内 someclass.respond
。 您甚至可以通过多种方式执行此操作。 您通常可以采用一个函数及其参数,然后将该函数应用于someclass.respond
内部的参数,或者可以直接在someclass.respond
内部进行调用。
让我们采用第一种方法,因为您已经说过不想重复异常处理。 我将这个新方法称为exception_catcher
:
def exception_catcher(func, *args):
try:
return func(*args)
except Exception as e:
pass # do whatever you want to the exception
现在, foo
上下文将如下所示:
def foo():
exception_catcher(somemodule.joule, someArgument, someStrategy)
需要注意的是exception_catcher
正在somemodule.joule
作为参数,而其余的参数将被传递到somemodule.joule
从内部exception_catcher
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.