[Twisted-Python] Trapping exceptions in Deferred

Mashiat Sarker Shakkhar mashiat.sarker at gmail.com
Tue May 12 10:48:00 MDT 2015


On Tue, May 12, 2015 at 11:33 AM, Louis D. Burr <ldanielburr at me.com> wrote:
>
> Hi Mashiat,

[...]

> This code sample does not indicate that you have actually assigned
log_ignore_network_errors as an errback on a Deferred anywhere.  If you can
provide a working code example that demonstrates your issue, it will be
easier to help you :)

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', Headers({'Content-Type':
['application/json']}), body)
d.addCallback(some_callback)
d.addErrback(log_ignore_network_errors)
```

[...]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: </pipermail/twisted-python/attachments/20150512/0cb62105/attachment-0002.html>


More information about the Twisted-Python mailing list