3
# Copyright (c) 2009 Twisted Matrix Laboratories.
4
# See LICENSE for details.
6
from twisted.internet import defer
7
from twisted.python import failure, util
10
This example shows an important concept that many deferred newbies
11
(myself included) have trouble understanding.
13
when an error occurs in a callback, the first errback after the error
14
occurs will be the next method called. (in the next example we'll
15
see what happens in the 'chain' after an errback).
18
class Counter(object):
23
print "we got an exception: %s" % (f.getTraceback(),)
26
def handleResult(result):
28
print "callback %s" % (Counter.num,)
29
print "\tgot result: %s" % (result,)
30
return "yay! handleResult was successful!"
32
def failAtHandlingResult(result):
34
print "callback %s" % (Counter.num,)
35
print "\tgot result: %s" % (result,)
36
print "\tabout to raise exception"
37
raise RuntimeError, "whoops! we encountered an error"
41
def behindTheScenes(result):
42
# equivalent to d.callback(result)
44
# now, let's make the error happen in the first callback
46
if not isinstance(result, failure.Failure): # ---- callback
48
result = failAtHandlingResult(result)
50
result = failure.Failure()
55
# note: this callback will be skipped because
58
if not isinstance(result, failure.Failure): # ---- callback
60
result = handleResult(result)
62
result = failure.Failure()
67
if not isinstance(result, failure.Failure): # ---- callback
71
result = handleFailure(result)
73
result = failure.Failure()
77
def deferredExample():
79
d.addCallback(failAtHandlingResult)
80
d.addCallback(handleResult)
81
d.addErrback(handleFailure)
86
if __name__ == '__main__':
87
behindTheScenes("success")
88
print "\n-------------------------------------------------\n"