Skip to content

Commit

Permalink
[skip ci] Use PEP 3151 exceptions + custom exception type
Browse files Browse the repository at this point in the history
Unit tests are not yet adopted.
  • Loading branch information
hannesweisbach committed Jan 30, 2024
1 parent db9658b commit 27c76be
Showing 1 changed file with 34 additions and 17 deletions.
51 changes: 34 additions & 17 deletions pycyphal/application/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import typing
import pathlib
import logging
import io
import itertools
import numpy as np
import pycyphal
Expand Down Expand Up @@ -749,36 +750,52 @@ class FileTimeoutError(pycyphal.application.NetworkTimeoutError):
"""


def _raise_if_error(error: Error, filename: str) -> None:
if error.value == Error.OK:
return

_logger.error(f"Decoded error value {error.value}")

exc_types = {
Error.NOT_FOUND: FileNotFoundError,
Error.ACCESS_DENIED: PermissionError,
Error.IS_DIRECTORY: IsADirectoryError,
Error.NOT_SUPPORTED: io.UnsupportedOperation,
}

if error.value in exc_types.keys():
raise exc_types.get(error.value)(filename)

raise FileError(error, filename)


_perror_uavcan = {
Error.OK: "OK",
Error.UNKNOWN_ERROR: "Unknown error",
Error.NOT_FOUND: "Not found", # FileNotFoundError
Error.NOT_FOUND: "Not found",
Error.IO_ERROR: "I/O error",
Error.ACCESS_DENIED: "Access denied", # PermissionError
Error.IS_DIRECTORY: "Is a directory", # IsADirectoryError
Error.ACCESS_DENIED: "Access denied",
Error.IS_DIRECTORY: "Is a directory",
Error.INVALID_VALUE: "Invalid value",
Error.FILE_TOO_LARGE: "File too large",
Error.OUT_OF_SPACE: "Out of space",
Error.NOT_SUPPORTED: "Not supported", # io.UnsupportedOperation
Error.NOT_SUPPORTED: "Not supported",
}


def _raise_if_error(error: Error, filename: str) -> None:
if error.value == Error.OK:
return

raise OSError(error.value, _perror_uavcan[error.value], filename)
# alternative:
# raise FileError(error, filename)


class FileError(OSError):
class FileError(Exception):
"""
Exception type specialized for uavcan.file.Error.
Exception type specialized for ``uavcan.file.Error``.
"""

def __init__(self, error: Error, filename: str):
super().__init__(error.value, _perror_uavcan[error.value], filename)
def __init__(self, error: Error, what: str):
error_desc = _perror_uavcan.get(error.value, _perror_uavcan[Error.UNKNOWN_ERROR])
super().__init__(f"Error: {error_desc} ({error.value}) {what}")
self._error_code = error.value

@property
def error_code(self):
return self._error_code


_logger = logging.getLogger(__name__)

0 comments on commit 27c76be

Please sign in to comment.