From 76f19a960aab8c00539b89b2b627071622a076fb Mon Sep 17 00:00:00 2001 From: Daniel Langbein Date: Sat, 1 Apr 2023 10:07:43 +0200 Subject: [PATCH] feat: custom exception classes --- src/netcup_dns/exception.py | 6 ++++++ src/netcup_dns/main.py | 10 +++++++--- 2 files changed, 13 insertions(+), 3 deletions(-) create mode 100644 src/netcup_dns/exception.py diff --git a/src/netcup_dns/exception.py b/src/netcup_dns/exception.py new file mode 100644 index 0000000..7115492 --- /dev/null +++ b/src/netcup_dns/exception.py @@ -0,0 +1,6 @@ +class UnknownIPException(Exception): + pass + + +class MultipleRecordsException(Exception): + pass diff --git a/src/netcup_dns/main.py b/src/netcup_dns/main.py index e797630..ebf5183 100644 --- a/src/netcup_dns/main.py +++ b/src/netcup_dns/main.py @@ -10,6 +10,8 @@ from typing import Type import requests from nc_dnsapi import Client, DNSRecord +from netcup_dns.exception import UnknownIPException, MultipleRecordsException + def main(): """ @@ -49,7 +51,7 @@ def main(): # Lazy: Only determine external IPv6 if an AAAA record shall be updated. destination = external_ipv6() else: - raise Exception(f'DNS record type {type_} is not supported.') + raise ValueError(f'DNS record type {type_} is not supported.') if update_record_destination(api, domain, hostname, type_, destination=destination): print(f'Set {hostname}.{domain} {type_} record to {destination}') @@ -86,13 +88,14 @@ def get_record(api: Client, domain: str, hostname: str, type_: str) -> DNSRecord :param hostname: :param type_: :return: The DNS record identified by `domain`, `hostname` and `type`. + :raises MultipleRecordsException: """ records: list[DNSRecord] = api.dns_records(domain) record: DNSRecord matches = [record for record in records if record.hostname == hostname and record.type == type_] if len(matches) != 1: - raise Exception(f'Expected one DNSRecord for {hostname}.{domain}, but got {len(matches)}') + raise MultipleRecordsException(f'Expected one DNSRecord for {hostname}.{domain}, but got {len(matches)}') return matches[0] @@ -127,6 +130,7 @@ def external_ip(version: Type[ipaddress.IPv4Address | ipaddress.IPv6Address], ti :param endpoints: List of webservices that return ones public IP IPv4/IPv6 address. :argument timeout: Timeout for each webservice in seconds. :return: Public IPv4/IPv6 address. + :raises UnknownIPException: """ if endpoints is None: if version == ipaddress.IPv4Address: @@ -159,7 +163,7 @@ def external_ip(version: Type[ipaddress.IPv4Address | ipaddress.IPv6Address], ti # Return IP address as string. return parsed_ip.exploded - raise Exception('Could not determine public IP address.') + raise UnknownIPException('Could not determine public IP address.') @lru_cache(maxsize=None)