[Twisted-Python] Handling errors when using deferToThread

Hello, In the twisted documentation there is this example: from twisted.internet import threads def doLongCalculation(): # .... do long calculation here ... return 3 def printResult(x): print x # run method in thread and get result as defer.Deferred d = threads.deferToThread(doLongCalculation) d.addCallback(printResult) This works well as long as doLongCalculation() doesn't fail for any reason. But if it does, how can it trigger an errBack? I want to do something like this: from twisted.internet import threads def doLongCalculation(): try: # .... do long calculation here ... except: < what can I return here to tell that the calculation failed? > return 3 def printResult(x): print x def badResult(failure): print "Calculation failed!" # run method in thread and get result as defer.Deferred d = threads.deferToThread(doLongCalculation) d.addCallbacks(printResult, badResult) Thanks in advance for your help, -- Pedro

On Fri, Oct 28, 2005 at 10:35:08AM -0400, Pedro Sanchez wrote: [...]
This works well as long as doLongCalculation() doesn't fail for any reason. But if it does, how can it trigger an errBack?
Just raise an exception.
The literal answer here is a bare raise statement. But better would be to not use the try-except at all. Try inserting something like "1/0" into doLongCalculation and see what happens. -Andrew.

def doLongCalculation(): return 1/0 This will raise a dividebyzero error. In which case your errback will be called. You don't need the try/except block because when an exception is raised your errback will be called instead of the callback. On 10/28/05, Pedro Sanchez <psanchez@nortel.com> wrote:

On Fri, Oct 28, 2005 at 10:35:08AM -0400, Pedro Sanchez wrote: [...]
This works well as long as doLongCalculation() doesn't fail for any reason. But if it does, how can it trigger an errBack?
Just raise an exception.
The literal answer here is a bare raise statement. But better would be to not use the try-except at all. Try inserting something like "1/0" into doLongCalculation and see what happens. -Andrew.

def doLongCalculation(): return 1/0 This will raise a dividebyzero error. In which case your errback will be called. You don't need the try/except block because when an exception is raised your errback will be called instead of the callback. On 10/28/05, Pedro Sanchez <psanchez@nortel.com> wrote:
participants (3)
-
Andrew Bennetts
-
Charlie Moad
-
Pedro Sanchez