如果存在所有域,则以下DNS异步客户端可以正常工作。
但是,如果域名不存在,则会引发DNSNameError异常,并且我的“try except”块不会捕获该异常。然后,其他域不解决。
我查看了DNSNameError和defer的文档,但我没有找到如何使用addErrback处理此错误,因为我使用了@inlineCallbacks。
问题:如何捕获 query()中的DNSNameError异常?
from itertools import cycle
from pprint import pprint
from twisted.names import client, dns
from twisted.internet.task import react
from twisted.internet import defer, reactor
def query(reactor, server, name):
resolver = client.Resolver(
resolv="/dev/null", servers=[(server, 53)], reactor=reactor)
try:
return resolver.lookupAddress(name)
except:
print "error query"
return defer.returnValue(([],[],[]))
@defer.inlineCallbacks
def main(reactor, names):
servers = ["4.2.2.1", "8.8.8.8"]
next_server = cycle(servers).next
results = []
for n in names:
try:
results.append(query(reactor, next_server(), n))
except:
print "error append"
try:
results = yield defer.gatherResults(results)
print "Success."
except:
print "Error result"
finally:
print "Shutting down"
reactor.stop()
pprint(zip(names, results))
if __name__ == '__main__':
main(reactor, ('google.com', 'notexist.www','google.fr',))
reactor.run()
结果:
$ipython twisteddns.py
ipython twisteddns.py
Error result
Shutting down
[('google.com', <Deferred at 0xad862ac>),
('notexist.www',
<Deferred at 0xad8666c current result: <twisted.python.failure.Failure <class 'twisted.names.error.DNSNameError'>>>),
('google.fr', <Deferred at 0xad869ac>)]
Unhandled error in Deferred:
Unhandled Error
Traceback (most recent call last):
Failure: twisted.names.error.DNSNameError: <twisted.names.dns.Message instance at 0xad86a6c>
答案 0 :(得分:1)
首先,永远不要在用returnValue
修饰的函数之外使用inlineCallbacks
。它没有任何意义,它会产生令人惊讶的结果,它会触发警告告诉你不要这样做,并且它可能会比在Twisted的未来版本中已经破坏的情况更糟糕。
您在query
中寻找的功能是defer.succeed
。如:
...
except:
print "error query"
return defer.succeed(([],[],[]))
但是,由于你<{1}}使用inlineCallbacks
,所以你应该将其添加为errback。
query