Reputation: 2120
I'm new to twisted and I'm having trouble to debug my code within the dataReceived
method of the twisted.internet.protocol.Protocol
object.
Given some code like this
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())
I couldn't find a way to add an Errback
on dataReceived
. Is there a way ? an other way to debug its behavior ?
Thanks in advance for your help.
Upvotes: 1
Views: 194
Reputation: 5107
You can't catch errors from dataReceived
directly since that function isn't a deferred
user's generally have control over. You can only call addErrback
on deferred
objects. Here is an example of how to catch errors:
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))
A deferred
is created in the dataReceived
function which will print data
and the invalid toto
variables. An errorback function (ie. self.error_func()
) is chained to catch errors that occur in display_data()
. 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
Upvotes: 1