[Twisted-Python] Trapping exceptions in Deferred

Louis D. Burr ldanielburr at me.com
Tue May 12 11:38:51 MDT 2015


Hi Mashiat,

> On May 12, 2015, at 11:48 AM, Mashiat Sarker Shakkhar <mashiat.sarker at gmail.com> wrote:
> 
[...]
> Alright. Below you can find a code snippet that is similar to my actual code. But my question is a little more generic - how do I catch exceptions that are encapsulated in a failure? If the actual exception is OpenSSL.SSL.Error, and it is wrapped in twisted.web._newclient.ResponseNeverReceived, how should my trap call look like?
> 
> ```
> imort json
> import StringIO
> from twisted.internet import reactor
> from twisted.internet.error import TimeoutError
> from twisted.web._newclient import ResponseNeverReceived
> from twisted.web.client import Agent, HTTPConnectionPool
> from twisted.web.client import FileBodyProducer
> 
> def some_callback(response):
>     pass
> 
> def log_ignore_network_errors(failure):
>     print failure.getErrorMessage()
>     failure.printTraceback()
>     failure.trap(TimeoutError, ResponseNeverReceived)
> 
> agent = Agent(reactor)
> body = FileBodyProducer(StringIO(json.dumps({'key': 'value'})))
> d = agent.request('POST', 'https://example.com <https://example.com/>', Headers({'Content-Type': ['application/json']}), body)
> d.addCallback(some_callback)
> d.addErrback(log_ignore_network_errors)
> ```

Thanks for providing the example.  Your code as presented here catches both TimeoutError and ResponseNeverReceived, so I am not sure why you think it isn’t working.  What are you seeing that indicates that the ResponseNeverReceived error is not being trapped?

As far as identifying/catching exceptions wrapped by ResponseNeverReceived, you can iterate over the “reasons” attribute (https://twistedmatrix.com/documents/current/api/twisted.web._newclient.ResponseNeverReceived.html <https://twistedmatrix.com/documents/current/api/twisted.web._newclient.ResponseNeverReceived.html>) and call either “trap” or “check” on each failure instance contained therein.

For any instance of twisted.python.failure, you can look at the “value” attribute to obtain the exception instance.

Hope this helps,

L. Daniel Burr

    
-------------- next part --------------
An HTML attachment was scrubbed...
URL: </pipermail/twisted-python/attachments/20150512/92e8dbad/attachment-0002.html>


More information about the Twisted-Python mailing list