扭曲:失败与错误
我什么时候应该使用 twisted.python.failure.Failure
,什么时候应该使用 twisted.internet.error.ConnectionDone
之类的东西?或者我应该这样做 twisted.python.failure.Failure(twisted.internet.error.ConnectionDone)
,如果是这样,在什么情况下我应该这样做?
When should I use a twisted.python.failure.Failure
, and when should I use something like twisted.internet.error.ConnectionDone
? Or should I do twisted.python.failure.Failure(twisted.internet.error.ConnectionDone)
, and if so, in what casese should I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Failure
表示异常和回溯(通常与当前堆栈跟踪不同)。当您构造异步异常时,您应该使用Failure
。因此,当您要触发带有错误的Deferred
时,或者当您要调用IProtocol.connectionLost
或ClientFactory.clientConnectionFailed 等方法时
。这是因为在这种情况下,您希望能够将与当前堆栈跟踪不同的堆栈跟踪与异常相关联。您不应使用
Failure(ConnectionDone)
,因为Failure
的正确单参数调用接受异常实例,而不是异常类。因此,请改用Failure(ConnectionDone())
。您还可以使用零参数形式创建新的Failure
:Failure()
。这仅在存在“当前”异常时有效,例如在except 语句套件中。它使用当前异常及其回溯构造
Failure
。您还可以构造一个包含三个参数的
Failure
:异常类、实例和回溯。这通常是使用 sys.exc_info() 的返回值来完成的。当您只想引发异常时,无需创建
Failure
。只需执行您通常在 Python 程序中执行的操作即可引发异常:raise SomeException(...)
。A
Failure
represents an exception and a traceback (often different from the current stack trace). You should useFailure
when you are constructing an asynchronous exception. So, when you're going to fire aDeferred
with an error, or when you're going to call a method likeIProtocol.connectionLost
orClientFactory.clientConnectionFailed
. This is because in such cases, you want the ability to associate a different stack trace with the exception than the current stack trace.You shouldn't use
Failure(ConnectionDone)
because the correct one-argument invocation ofFailure
accepts an exception instance, not an exception class. So, instead, useFailure(ConnectionDone())
. You can also use the zero-argument form to create a newFailure
:Failure()
. This only works when there is a "current" exception, eg in the suite of anexcept
statement. It constructs theFailure
using that current exception, as well as its traceback.You can also construct a
Failure
with three-arguments, an exception class, instance, and traceback. This is most commonly done using the return value ofsys.exc_info()
.When you just want to raise an exception, you don't need to create a
Failure
. Just do what you'd normally do in a Python program to raise an exception:raise SomeException(...)
.