[Twisted-Python] How to chain deferred calls

Terry Jones terry at jon.es
Thu Oct 22 21:13:00 EDT 2009


>>>>> "vitaly" == vitaly  <vitaly at synapticvision.com> writes:

vitaly> Thank you a lot for pointing me to the Twisted doc-s, but we're
vitaly> discussing the following snippet:
[snip]
vitaly> and basically, I've expected in case of exception
vitaly> self.handleFailure1() to be called, but I don't see it happen.

The reason you're not seeing handleFailure1 being called is that the
exception is not occurring in the context of deferred processing. You've
got a regular Python function call, a regular exception is raised, etc.
Twisted and its deferred do not / cannot alter that behavior.

What they *can* do is handle exceptions and turn them into failures and
route the failure to an errback chain *in the context of calling functions
that have been added to a deferred*.  Because your abc1 has not been added
to any deferred's call/errback chain, none of that happens when your
exception is raised.

If your code looked like this (pseudocode), you would see the exception

    return (
         self.abc1().
         addErrback(self.handleFailure1).
         addCallback(self.abc2,args).
         addCallback(self.abc3).
         addErrback(self.handleFailure2)
    )

    def abc1(self):
        d = defer.Deferred()
        d.addCallback(raiser)
        d.callback(1)
        return d

    def raiser(self, _):
        raise Exception("Error11")

Because the thing that raises is being called by Twisted's deferred class,
and its exception is caught and routed to d's errback chain and winds up in
the handleFailure1 method.

Does that make sense?

Terry



More information about the Twisted-Python mailing list