How to debug Protocol.dataReceived in Twisted
<p>I'm new to twisted and I'm having trouble to debug my code within the <code>dataReceived</code> method of the <code>twisted.internet.protocol.Protocol</code> object.</p>

<p>Given some code like this</p>

<pre><code>class Printer(Protocol):
    def dataReceived(self, data):
        print data # Works perfectly
        print toto # should trigger some error since "toto" is not defined
...
response.deliverBody(Printer())
</code></pre>

<p>I couldn't find a way to add an <code>Errback</code> on <code>dataReceived</code>. Is there a way ? an other way to debug its behavior ?</p>

<p>Thanks in advance for your help.</p>

<p>You can't catch errors from <code>dataReceived</code> directly since that function isn't a <code>deferred</code> user's generally have control over.  You can only call <code>addErrback</code> on <code>deferred</code> objects.  Here is an example of how to catch errors:</p>

<pre><code>from twisted.internet.protocol import Protocol
from twisted.internet.defer import Deferred

class Printer(Protocol):
    def dataReceived(self, data):
        d = Deferred()
        d.addCallback(self.display_data)
        d.addErrback(self.error_func)
        d.callback(data)

    def display_data(self, data):
        print(data)
        print(toto)    # this will raise NameError error

    def error_func(self, error):
        print('[!] Whoops here is the error: {0}'.format(error))
</code></pre>

<p>A <code>deferred</code> is created in the <code>dataReceived</code> function which will print <code>data</code> and the invalid <code>toto</code> variables.  An errorback function (ie. <code>self.error_func()</code>) is chained to catch errors that occur in <code>display_data()</code>. You should strive very hard to not have errors in the dataReceived function itself. This isn't always possible but one should try.  Hope this helps</p>

python asynchronous twisted