awslambda函数中的异常处理

2024-06-03 20:41:22 发布

您现在位置:Python中文网/ 问答频道 /正文

在尝试实现DNSRequest时,我还需要做一些异常处理,并注意到一些奇怪的东西。以下代码能够捕获DNS请求超时

def lambda_handler(event, context):

    hostname = "google.de"
    dnsIpAddresses = event['dnsIpAddresses']
    dnsResolver = dns.resolver.Resolver()
    dnsResolver.lifetime = 1.0
    result = {}

    for dnsIpAddress in dnsIpAddresses:
        dnsResolver.nameservers = [dnsIpAddress]

        try:
           myAnswers = dnsResolver.query(hostname, "A")
           print(myAnswers)
           result[dnsIpAddress] = "SUCCESS"
        except dns.resolver.Timeout:
           print("caught Timeout exception")
           result[dnsIpAddress] = "FAILURE"
        except dns.exception.DNSException:
           print("caught DNSException exception")
           result[dnsIpAddress] = "FAILURE"
        except:
           result[dnsIpAddress] = "FAILURE"
           print("caught general exception")

    return result

现在,如果我删除了Timeout块,并假设将发生超时,则在DNSException上

caught DNSException exception

永远不会出现。在

现在,如果我删除DNSException块,并假设将发生超时,则消息

caught general exception

永远不会出现。在

但是超时扩展了DNSException,DNSException扩展了Exception。我期望至少通用的expect块应该可以工作。在

我错过了什么?在


Tags: eventfailurednstimeoutexceptionresulthostnameprint