Skip to content

Commit

Permalink
Uniform exception names (#225)
Browse files Browse the repository at this point in the history
* Make Errors end with Error, warnings have no suffix.
  • Loading branch information
terjekv authored May 12, 2024
1 parent 98ea140 commit 7123311
Show file tree
Hide file tree
Showing 8 changed files with 75 additions and 71 deletions.
18 changes: 8 additions & 10 deletions mreg_cli/api/abstracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@
from mreg_cli.api.endpoints import Endpoint
from mreg_cli.api.history import HistoryItem, HistoryResource
from mreg_cli.exceptions import (
CreateFailure,
CreateError,
EntityAlreadyExists,
EntityNotFound,
GetFailure,
GetError,
InternalError,
PatchFailure,
PatchError,
)
from mreg_cli.outputmanager import OutputManager
from mreg_cli.utilities.api import (
Expand Down Expand Up @@ -332,7 +332,7 @@ def refetch(self) -> Self:

obj = self.__class__.get_by_id(lookup)
if not obj:
raise GetFailure(f"Could not refresh {self.__class__.__name__} with ID {identifier}.")
raise GetError(f"Could not refresh {self.__class__.__name__} with ID {identifier}.")

return obj

Expand Down Expand Up @@ -362,11 +362,9 @@ def patch(self, fields: dict[str, Any]) -> Self:
try:
nval = getattr(new_object, field_name)
except AttributeError as e:
raise PatchFailure(
f"Could not get value for {field_name} in patched object."
) from e
raise PatchError(f"Could not get value for {field_name} in patched object.") from e
if value and str(nval) != str(value):
raise PatchFailure(
raise PatchError(
# Should this reference `field_name` instead of `key`?
f"Patch failure! Tried to set {key} to {value}, but server returned {nval}."
)
Expand Down Expand Up @@ -411,7 +409,7 @@ def create(cls, params: dict[str, str | None]) -> Self | None:
if obj:
return obj

raise GetFailure(f"Could not fetch object from location {location}.")
raise GetError(f"Could not fetch object from location {location}.")

# else:
# Lots of endpoints don't give locations on creation,
Expand All @@ -420,7 +418,7 @@ def create(cls, params: dict[str, str | None]) -> Self | None:
# cli_warning("No location header in response.")

else:
raise CreateFailure(f"Failed to create {cls} with {params} @ {cls.endpoint()}.")
raise CreateError(f"Failed to create {cls} with {params} @ {cls.endpoint()}.")

return None

Expand Down
27 changes: 13 additions & 14 deletions mreg_cli/api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,18 @@
from mreg_cli.config import MregCliConfig
from mreg_cli.exceptions import (
CliWarning,
DeleteFailure,
DeleteError,
EntityAlreadyExists,
EntityNotFound,
EntityOwnershipMismatch,
InputFailure,
InternalError,
IsNotANetwork,
IsNotAnIPAddress,
IsNotAnIPv4Address,
IsNotAnIPv6Address,
InvalidIPAddress,
InvalidIPv4Address,
InvalidIPv6Address,
MultipleEntititesFound,
UnexpectedAPIData,
ValidationFailure,
UnexpectedDataError,
ValidationError,
)
from mreg_cli.outputmanager import OutputManager
from mreg_cli.types import IP_AddressT, IP_NetworkT, IP_Version
Expand Down Expand Up @@ -83,25 +82,25 @@ def is_ipv4(self) -> bool:
def as_ipv4(self) -> ipaddress.IPv4Address:
"""Return the value as an IPv4 address."""
if not self.is_ipv4():
raise IsNotAnIPv4Address("Value is not an IPv4 address.")
raise InvalidIPv4Address("Value is not an IPv4 address.")
return cast(ipaddress.IPv4Address, self.ip_or_network)

def as_ipv6(self) -> ipaddress.IPv6Address:
"""Return the value as an IPv6 address."""
if not self.is_ipv6():
raise IsNotAnIPv6Address("Value is not an IPv6 address.")
raise InvalidIPv6Address("Value is not an IPv6 address.")
return cast(ipaddress.IPv6Address, self.ip_or_network)

def as_ip(self) -> IP_AddressT:
"""Return the value as an IP address."""
if not self.is_ip():
raise IsNotAnIPAddress(f"{self.ip_or_network} is not an IP address.")
raise InvalidIPAddress(f"{self.ip_or_network} is not an IP address.")
return cast(IP_AddressT, self.ip_or_network)

def as_network(self) -> IP_NetworkT:
"""Return the value as a network."""
if not self.is_network():
raise IsNotANetwork(f"{self.ip_or_network} is not a network.")
raise InvalidNetworkError(f"{self.ip_or_network} is not a network.")
return cast(IP_NetworkT, self.ip_or_network)

def is_ipv6(self) -> bool:
Expand Down Expand Up @@ -374,7 +373,7 @@ def get_from_hostname(cls, hostname: HostT) -> Delegation | Zone | None:
if "zone" in zoneblob:
return ForwardZone(**zoneblob["zone"])

raise UnexpectedAPIData(f"Unexpected response from server: {zoneblob}")
raise UnexpectedDataError(f"Unexpected response from server: {zoneblob}")


class Delegation(FrozenModelWithTimestamps, WithZone):
Expand Down Expand Up @@ -1496,7 +1495,7 @@ def delete(self) -> bool:
# in the endpoint URL...
op = delete(Endpoint.Hosts.with_id(str(self.name)))
if not op:
raise DeleteFailure(f"Failed to delete host {self.name}, operation failed.")
raise DeleteError(f"Failed to delete host {self.name}, operation failed.")

return op.status_code >= 200 and op.status_code < 300

Expand Down Expand Up @@ -1770,7 +1769,7 @@ def resolve_zone(
if data_as_dict["zone"]:
zone = Zone(**data_as_dict["zone"])
if validate_zone_resolution and zone.id != self.zone:
raise ValidationFailure(f"Expected zone ID {self.zone} but resovled as {zone.id}.")
raise ValidationError(f"Expected zone ID {self.zone} but resovled as {zone.id}.")
return zone

if data_as_dict["delegation"]:
Expand Down
4 changes: 2 additions & 2 deletions mreg_cli/commands/host_submodules/a_aaaa.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from mreg_cli.api.models import Host, HostList, IPAddress, MACAddressField, Network, NetworkOrIP
from mreg_cli.commands.host import registry as command_registry
from mreg_cli.exceptions import (
DeleteFailure,
DeleteError,
EntityAlreadyExists,
EntityNotFound,
ForceMissing,
Expand Down Expand Up @@ -143,7 +143,7 @@ def _ip_remove(args: argparse.Namespace, ipversion: IP_Version) -> None:
if host_ip.delete():
cli_info(f"Removed ipaddress {args.ip} from {host}", print_msg=True)
else:
raise DeleteFailure(f"Failed to remove ipaddress {args.ip} from {host}")
raise DeleteError(f"Failed to remove ipaddress {args.ip} from {host}")


def _add_ip(
Expand Down
8 changes: 4 additions & 4 deletions mreg_cli/commands/host_submodules/bacnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
from mreg_cli.api.models import BacnetID, Host
from mreg_cli.commands.host import registry as command_registry
from mreg_cli.exceptions import (
CreateFailure,
DeleteFailure,
CreateError,
DeleteError,
EntityAlreadyExists,
EntityNotFound,
EntityOwnershipMismatch,
Expand Down Expand Up @@ -56,7 +56,7 @@ def bacnetid_add(args: argparse.Namespace) -> None:
if validator and validator.hostname == host.name.hostname:
cli_info(f"Assigned BACnet ID {validator.id} to {validator.hostname}.", print_msg=True)
else:
raise CreateFailure(f"Failed to assign BACnet ID {args.id} to {host.name.hostname}.")
raise CreateError(f"Failed to assign BACnet ID {args.id} to {host.name.hostname}.")


@command_registry.register_command(
Expand All @@ -80,7 +80,7 @@ def bacnetid_remove(args: argparse.Namespace) -> None:
if host_bacnet.delete():
cli_info(f"Unassigned BACnet ID {host_bacnet.id} from {host.name}.", print_msg=True)
else:
raise DeleteFailure(f"Failed to unassign BACnet ID {host_bacnet.id} from {host.name}.")
raise DeleteError(f"Failed to unassign BACnet ID {host_bacnet.id} from {host.name}.")


@command_registry.register_command(
Expand Down
12 changes: 6 additions & 6 deletions mreg_cli/commands/host_submodules/cname.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@
from mreg_cli.api.models import CNAME, ForwardZone, Host, HostT
from mreg_cli.commands.host import registry as command_registry
from mreg_cli.exceptions import (
CreateFailure,
DeleteFailure,
CreateError,
DeleteError,
EntityAlreadyExists,
EntityNotFound,
EntityOwnershipMismatch,
InputFailure,
PatchFailure,
PatchError,
)
from mreg_cli.log import cli_info
from mreg_cli.types import Flag
Expand Down Expand Up @@ -66,7 +66,7 @@ def cname_add(args: argparse.Namespace) -> None:
if cname:
cli_info(f"Added CNAME {cname.name} for {host.name.hostname}.", print_msg=True)
else:
raise CreateFailure(f"Failed to add CNAME {alias} for {host.name.hostname}.")
raise CreateError(f"Failed to add CNAME {alias} for {host.name.hostname}.")


@command_registry.register_command(
Expand Down Expand Up @@ -108,7 +108,7 @@ def cname_remove(args: argparse.Namespace) -> None:
if cname.delete():
cli_info(f"Removed CNAME {cname.name} for {host.name}.", print_msg=True)
else:
raise DeleteFailure(f"Failed to remove CNAME {cname.name} for {host.name}.")
raise DeleteError(f"Failed to remove CNAME {cname.name} for {host.name}.")


@command_registry.register_command(
Expand Down Expand Up @@ -143,7 +143,7 @@ def cname_replace(args: argparse.Namespace) -> None:
f"Moved CNAME alias {cname}: {old_host.name.hostname} -> {host.name}.", print_msg=True
)
else:
raise PatchFailure(f"Failed to move CNAME alias {cname}.")
raise PatchError(f"Failed to move CNAME alias {cname}.")


@command_registry.register_command(
Expand Down
14 changes: 7 additions & 7 deletions mreg_cli/commands/host_submodules/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@
from mreg_cli.api.models import ForwardZone, Host, HostList, HostT, MACAddressField, NetworkOrIP
from mreg_cli.commands.host import registry as command_registry
from mreg_cli.exceptions import (
CreateFailure,
DeleteFailure,
CreateError,
DeleteError,
EntityAlreadyExists,
EntityNotFound,
EntityOwnershipMismatch,
ForceMissing,
InputFailure,
PatchFailure,
PatchError,
)
from mreg_cli.log import cli_info
from mreg_cli.types import Flag
Expand Down Expand Up @@ -129,7 +129,7 @@ def add(args: argparse.Namespace) -> None:

host = Host.create(data)
if not host:
raise CreateFailure("Failed to add host.")
raise CreateError("Failed to add host.")

if macaddress is not None:
if ip:
Expand Down Expand Up @@ -291,7 +291,7 @@ def forced(override_required: str | None = None) -> bool:
if host.delete():
cli_info(f"removed {host.name}", print_msg=True)
else:
raise DeleteFailure(f"failed to remove {host.name}")
raise DeleteError(f"failed to remove {host.name}")


@command_registry.register_command(
Expand Down Expand Up @@ -451,7 +451,7 @@ def set_comment(args: argparse.Namespace) -> None:
updated_host = host.set_comment(args.comment)

if not updated_host:
raise PatchFailure(f"Failed to update comment of {host.name}")
raise PatchError(f"Failed to update comment of {host.name}")

cli_info(
f"Updated comment of {host} to {args.comment}",
Expand All @@ -477,7 +477,7 @@ def set_contact(args: argparse.Namespace) -> None:
updated_host = host.set_contact(args.contact)

if not updated_host:
raise PatchFailure(f"Failed to update contact of {host.name}")
raise PatchError(f"Failed to update contact of {host.name}")

cli_info(f"Updated contact of {host} to {args.contact}", print_msg=True)

Expand Down
Loading

0 comments on commit 7123311

Please sign in to comment.