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?
When should I use a twisted.python.failure.Failure , and when should I use something like
Share
A
Failurerepresents an exception and a traceback (often different from the current stack trace). You should useFailurewhen you are constructing an asynchronous exception. So, when you’re going to fire aDeferredwith an error, or when you’re going to call a method likeIProtocol.connectionLostorClientFactory.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 ofFailureaccepts 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 anexceptstatement. It constructs theFailureusing that current exception, as well as its traceback.You can also construct a
Failurewith 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(...).