开发者

twisted: Failure vs. Error

开发者 https://www.devze.com 2023-01-11 13:08 出处:网络
When should I use a twisted.python.failure.Failure, and when should I use somethi开发者_开发知识库ng like twisted.internet.error.ConnectionDone? Or should I do twisted.python.failure.Failure(twisted.i

When should I use a twisted.python.failure.Failure, and when should I use somethi开发者_开发知识库ng 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?


A Failure represents an exception and a traceback (often different from the current stack trace). You should use Failure when you are constructing an asynchronous exception. So, when you're going to fire a Deferred with an error, or when you're going to call a method like IProtocol.connectionLost or ClientFactory.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 of Failure accepts an exception instance, not an exception class. So, instead, use Failure(ConnectionDone()). You can also use the zero-argument form to create a new Failure: Failure(). This only works when there is a "current" exception, eg in the suite of an except statement. It constructs the Failure 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 of sys.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(...).

0

精彩评论

暂无评论...
验证码 换一张
取 消