# Buggy code
def get_domain_mx_list(domain):
    """Return a list of MX IP address for domain."""
    result = []
    logger = logging.getLogger("modoboa.admin")
    dns_server = param_tools.get_global_parameter("custom_dns_server")
    if dns_server:
        resolver = dns.resolver.Resolver()
        resolver.nameservers = [dns_server]
    else:
        resolver = dns.resolver

    try:
        dns_answers = resolver.query(domain, "MX")
    except dns.resolver.NXDOMAIN as e:
        logger.error(_("No DNS records found for %s") % domain, exc_info=e)
    except dns.resolver.NoAnswer as e:
        logger.error(_("No MX record for %s") % domain, exc_info=e)
    except dns.resolver.NoNameservers as e:
        logger.error(_("No working name servers found"), exc_info=e)
    except dns.resolver.Timeout as e:
        logger.warning(
            _("DNS resolution timeout, unable to query %s at the moment") % domain,
            exc_info=e,
        )
    else:
        for dns_answer in dns_answers:
            for rtype in ["A", "AAAA"]:
                try:
                    mx_domain = dns_answer.exchange.to_unicode(
                        omit_final_dot=True, idna_codec=IDNA_2008_UTS_46
                    )
                    ip_answers = resolver.query(mx_domain, rtype)
                except dns.resolver.NXDOMAIN as e:
                    logger.error(
                        _("No {type} record found for MX {mx}").format(
                            type=rtype, mx=domain
                        ),
                        exc_info=e,
                    )
                else:
                    for ip_answer in ip_answers:
                        try:
                            address_smart = smart_text(ip_answer.address)
                            mx_ip = ipaddress.ip_address(address_smart)
                        except ValueError as e:
                            logger.warning(
                                _(
                                    "Invalid IP address format for {domain}; {addr}"
                                ).format(
                                    domain=mx_domain, addr=smart_text(ip_answer.address)
                                ),
                                exc_info=e,
                            )
                        else:
                            result.append((mx_domain, mx_ip))
    return result


# Traceback (KeyError)
Traceback (most recent call last):
File "/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py", line 215, in __init__
rdclass, rdtype)
File "/srv/modoboa/env3/lib/python3.5/site-packages/dns/message.py", line 352, in find_rrset
raise KeyError
KeyError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py", line 225, in __init__
dns.rdatatype.CNAME)
File "/srv/modoboa/env3/lib/python3.5/site-packages/dns/message.py", line 352, in find_rrset
raise KeyError
KeyError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/srv/modoboa/instance/manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/srv/modoboa/env3/lib/python3.5/site-packages/subcommand/base.py", line 53, in run_from_argv
return super(SubcommandCommand, self).run_from_argv(argv)
File "/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/srv/modoboa/env3/lib/python3.5/site-packages/subcommand/base.py", line 84, in handle
return command.run_from_argv(argv)
File "/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/srv/modoboa/env3/lib/python3.5/site-packages/modoboa/admin/management/commands/subcommands/_mx.py", line 244, in handle
self.check_domain(domain, **options)
File "/srv/modoboa/env3/lib/python3.5/site-packages/modoboa/admin/management/commands/subcommands/_mx.py", line 191, in check_domain
models.MXRecord.objects.get_or_create_for_domain(domain, ttl))
File "/srv/modoboa/env3/lib/python3.5/site-packages/modoboa/admin/models/mxrecord.py", line 47, in get_or_create_for_domain
domain_mxs = lib.get_domain_mx_list(domain.name)
File "/srv/modoboa/env3/lib/python3.5/site-packages/modoboa/admin/lib.py", line 202, in get_domain_mx_list
ip_answers = resolver.query(mx_domain, rtype)
File "/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py", line 1132, in query
raise_on_no_answer, source_port)
File "/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py", line 1053, in query
raise_on_no_answer)
File "/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py", line 234, in __init__
raise NoAnswer(response=response)
dns.resolver.NoAnswer: The DNS response does not contain an answer to the question: mail.toto.com. IN AAAA

# Fixed code
def get_domain_mx_list(domain):
    """Return a list of MX IP address for domain."""
    result = []
    logger = logging.getLogger("modoboa.admin")
    dns_server = param_tools.get_global_parameter("custom_dns_server")
    if dns_server:
        resolver = dns.resolver.Resolver()
        resolver.nameservers = [dns_server]
    else:
        resolver = dns.resolver

    try:
        dns_answers = resolver.query(domain, "MX")
    except dns.resolver.NXDOMAIN as e:
        logger.error(_("No DNS records found for %s") % domain, exc_info=e)
    except dns.resolver.NoAnswer as e:
        logger.error(_("No MX record for %s") % domain, exc_info=e)
    except dns.resolver.NoNameservers as e:
        logger.error(_("No working name servers found"), exc_info=e)
    except dns.resolver.Timeout as e:
        logger.warning(
            _("DNS resolution timeout, unable to query %s at the moment") % domain,
            exc_info=e,
        )
    else:
        for dns_answer in dns_answers:
            for rtype in ["A", "AAAA"]:
                try:
                    mx_domain = dns_answer.exchange.to_unicode(
                        omit_final_dot=True, idna_codec=IDNA_2008_UTS_46
                    )
                    ip_answers = resolver.query(mx_domain, rtype)
                except dns.resolver.NXDOMAIN as e:
                    logger.error(
                        _("No {type} record found for MX {mx}").format(
                            type=rtype, mx=domain
                        ),
                        exc_info=e,
                    )
                except dns.resolver.NoAnswer:
                    pass
                else:
                    for ip_answer in ip_answers:
                        try:
                            address_smart = smart_text(ip_answer.address)
                            mx_ip = ipaddress.ip_address(address_smart)
                        except ValueError as e:
                            logger.warning(
                                _(
                                    "Invalid IP address format for {domain}; {addr}"
                                ).format(
                                    domain=mx_domain, addr=smart_text(ip_answer.address)
                                ),
                                exc_info=e,
                            )
                        else:
                            result.append((mx_domain, mx_ip))
    return result