[Twisted-Python] How to chain deferred calls

Andrew Bennetts andrew at bemusement.org
Thu Oct 22 21:37:19 EDT 2009

vitaly at synapticvision.com wrote:
> def abc1(self):
>      if t.test() is None:
>        raise Exception("Error11")
>      else:
>        d = defer.Deferred()
>        d.callback(1)
>        return d
> and basically, I've expected in case of exception  
> self.handleFailure1() to be called, but I don't see it happen.

This is a function that either returns a Deferred or raises an exception.  This
isn't a Twisted issue, it's simply a Python one: in “func1().func2()”, if func1
raises an exception then func2 will not be invoked.  That's fundamental to what
raising an exception in Python means.

If you want to convert this to something that always returns a Deferred, you can
either rewrite it, e.g. using “return defer.fail(Exception('Error11'))”, or use
maybeDeferred which will intercept exceptions for you, e.g.:

    return (
	# etc...

You can find maybeDeferred in the twisted.internet.defer module.


More information about the Twisted-Python mailing list