Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions docs/Exception_Guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@ project's `EXIT_CODES` mapping.
```python
try:
import important_module
except ImportError:
except ImportError as _cause:
raise ModuleNotFoundError(
"[CWE-758] Module failed to import."
) from None
) from _cause
```

**Example 2**: In `multicast/hear.py`, handling errors during module import.
Expand Down Expand Up @@ -97,8 +97,8 @@ project's `EXIT_CODES` mapping.
In `multicast/__main__.py`, wrapping the original `ImportError` to provide additional context.

```python
except ImportError as impErr:
raise ImportError("[CWE-440] Error Importing Python") from impErr
except ImportError as _cause:
raise ImportError("[CWE-440] Error Importing Python") from _cause
```

#### `OSError`
Expand All @@ -110,8 +110,8 @@ project's `EXIT_CODES` mapping.
In `multicast/recv.py`, when a socket operation fails.

```python
except OSError as err:
raise OSError("[CWE-440] Socket operation failed.") from err
except OSError as _cause:
raise OSError("[CWE-440] Socket operation failed.") from _cause
```

#### `FileNotFoundError`
Expand Down Expand Up @@ -263,8 +263,8 @@ context.
Handling import errors with additional context.

```python
except ImportError as impErr:
raise ImportError("[CWE-440] Error Importing Python") from impErr
except ImportError as _cause:
raise ImportError("[CWE-440] Error Importing Python") from _cause
```

### Example 4: `ShutdownCommandReceived` in `multicast/hear.py`
Expand All @@ -285,8 +285,8 @@ context.
Indicating a socket operation failure.

```python
except OSError as err:
raise OSError("[CWE-474] Socket operation failed.") from err
except OSError as _cause:
raise OSError("[CWE-474] Socket operation failed.") from _cause
```

### Example 6: `KeyboardInterrupt` in `multicast/hear.py`
Expand All @@ -296,8 +296,8 @@ context.
Handling user interruption (e.g., pressing Ctrl+C).

```python
except KeyboardInterrupt as key_err:
raise KeyboardInterrupt("User interrupted the process.") from key_err
except KeyboardInterrupt as _cause:
raise KeyboardInterrupt("User interrupted the process.") from _cause
```

## Error Handling Practices
Expand Down
10 changes: 5 additions & 5 deletions docs/FAQ.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,11 +138,11 @@ try:
except Exception:
p.join()
raise RuntimeError("multicast seems to have failed.")

# clean up some stuff
p.join() # if not already handled don't forget to join the process and other overhead
didWork = (int(p.exitcode) <= int(0)) # if you use a loop and need to know the exit code

finally:
# clean up some stuff
if p:
p.join() # if not already handled don't forget to join the process and other overhead
didWork = (p is not None and int(p.exitcode) <= int(0)) # if you use a loop and need to know the exit code
```

> [!WARNING]
Expand Down
13 changes: 7 additions & 6 deletions docs/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,14 @@ _fixture_SAY_args = [
try:
multicast.__main__.McastDispatch().doStep("SAY", _fixture_SAY_args)
# Hint: use a loop to repeat or different arguments to vary message.
except Exception:
except multicast.exceptions.CommandExecutionError as baton:
p.join()
raise RuntimeError("Multicast operation failed.")

# clean up some stuff
p.join() # if not already handled don't forget to join the process and other overhead
didWork = (int(p.exitcode) <= int(0)) # if you use a loop and need to know the exit code
raise RuntimeError("Multicast operation failed.") from baton
finally:
# clean up some stuff
if p:
p.join() # if not already handled don't forget to join the process and other overhead
didWork = (int(p.exitcode) <= int(0)) # if you use a loop and need to know the exit code

```

Expand Down
26 changes: 15 additions & 11 deletions multicast/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"""__prologue__""",
"""__doc__""",
"""exceptions""",
"""exceptions.CommandExecutionError""",
"""exceptions.CommandExecutionError""", # skipcq: PYL-E0603 -- imports ok
"""exceptions.get_exit_code_from_exception""",
"""exceptions.exit_on_exception""",
"""get_exit_code_from_exception""",
Expand All @@ -43,13 +43,13 @@
"""skt.__package__""",
"""skt.__module__""",
"""skt.__name__""",
"""skt.__file__""",
"""skt.__file__""", # skipcq: PYL-E0603 -- shadow imports ok
"""skt.genSocket""",
"""skt.genSocket.__func__""",
"""genSocket""",
"""skt.endSocket""",
"""skt.endSocket.__func__""",
"""endSocket""",
"""skt.genSocket.__func__""", # skipcq: PYL-E0603 -- shadow imports ok
"""genSocket""", # skipcq: PYL-E0603 -- imports ok
"""skt.endSocket""", # skipcq: PYL-E0603 -- imports ok
"""skt.endSocket.__func__""", # skipcq: PYL-E0603 -- shadow imports ok
"""endSocket""", # skipcq: PYL-E0603 -- imports ok
"""EXIT_CODES""",
"""EXCEPTION_EXIT_CODES""",
"""_BLANK""",
Expand All @@ -61,9 +61,9 @@
"""recv""",
"""send""",
"""hear""",
"""recv.McastRECV""",
"""send.McastSAY""",
"""hear.McastHEAR""",
"""recv.McastRECV""", # skipcq: PYL-E0603 -- imports ok
"""send.McastSAY""", # skipcq: PYL-E0603 -- imports ok
"""hear.McastHEAR""", # skipcq: PYL-E0603 -- imports ok
]

__package__ = "multicast" # skipcq: PYL-W0622
Expand Down Expand Up @@ -440,7 +440,7 @@
if abc.__name__ is None:
raise ModuleNotFoundError("FAIL: we could not import Abstract base class. ABORT.") from None

if 'multicast.exceptions' not in sys.modules:
if "multicast.exceptions" not in sys.modules:
# pylint: disable=cyclic-import - skipcq: PYL-R0401, PYL-C0414
from . import exceptions # pylint: disable=cyclic-import - skipcq: PYL-R0401, PYL-C0414
else: # pragma: no branch
Expand Down Expand Up @@ -742,6 +742,7 @@ def doStep(self, *args, **kwargs) -> tuple: # pragma: no cover


if "multicast.skt" not in sys.modules:
# pylint: disable=cyclic-import - skipcq: PYL-R0401, PYL-C0414
from . import skt as skt # pylint: disable=cyclic-import - skipcq: PYL-R0401, PYL-C0414
else: # pragma: no branch
global skt # skipcq: PYL-W0604
Expand All @@ -754,18 +755,21 @@ def doStep(self, *args, **kwargs) -> tuple: # pragma: no cover
"""See multicast.skt.endSocket."""

if "multicast.recv" not in sys.modules:
# pylint: disable=cyclic-import - skipcq: PYL-R0401, PYL-C0414
from . import recv as recv # pylint: disable=cyclic-import - skipcq: PYL-R0401, PYL-C0414
else: # pragma: no branch
global recv # skipcq: PYL-W0604
recv = sys.modules["multicast.recv"]

if "multicast.send" not in sys.modules:
# pylint: disable=cyclic-import - skipcq: PYL-R0401, PYL-C0414
from . import send as send # pylint: disable=cyclic-import - skipcq: PYL-R0401, PYL-C0414
else: # pragma: no branch
global send # skipcq: PYL-W0604
send = sys.modules["multicast.send"]

if "multicast.hear" not in sys.modules:
# pylint: disable=cyclic-import - skipcq: PYL-R0401, PYL-C0414
from . import hear as hear # pylint: disable=cyclic-import - skipcq: PYL-R0401, PYL-C0414
else: # pragma: no branch
global hear # skipcq: PYL-W0604
Expand Down
20 changes: 10 additions & 10 deletions multicast/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,9 @@

try:
from . import sys
except ImportError as impErr:
except ImportError as baton:
# Throw more relevant Error
raise ImportError(str("[CWE-440] Error Importing Python")) from impErr
raise ImportError("[CWE-440] Error Importing Python") from baton

if "multicast.__version__" not in sys.modules:
from . import __version__ as __version__ # skipcq: PYL-C0414
Expand Down Expand Up @@ -596,8 +596,8 @@ def useTool(tool, **kwargs):
if (tool is not None) and (tool in cached_list):
try:
(_is_done, theResult) = TASK_OPTIONS[tool].__call__([], **kwargs)
except Exception as e: # pragma: no branch
theResult = f"CRITICAL - Attempted '[{tool}]: {kwargs}' just failed! :: {e}" # noqa
except Exception as _cause: # pragma: no branch
theResult = f"CRITICAL - Attempted '[{tool}]: {kwargs}' just failed! :: {_cause}" # noqa
_is_done = False
return (_is_done, theResult) # noqa

Expand Down Expand Up @@ -626,18 +626,18 @@ def doStep(self, *args, **kwargs):
__EXIT_MSG = (70, _TOOL_MSG)
if (sys.stdout.isatty()): # pragma: no cover
print(str(_TOOL_MSG))
except Exception as err: # pragma: no branch
exit_code = exceptions.get_exit_code_from_exception(err)
except Exception as _cause: # pragma: no branch
exit_code = exceptions.get_exit_code_from_exception(_cause)
__EXIT_MSG = (
False,
f"CRITICAL - Attempted '[{__name__}]: {args}' just failed! :: {exit_code} {err}" # noqa
1,
f"CRITICAL - Attempted '[{__name__}]: {args}' just failed! :: {exit_code} {_cause}" # noqa
)
if (sys.stderr.isatty()):
print(
"WARNING - An error occurred while handling the arguments. Refused.",
file=sys.stderr
file=sys.stderr,
)
print(f"{exceptions.EXIT_CODES[exit_code][1]}: {err}\n{err.args}", file=sys.stderr)
print(f"{exceptions.EXIT_CODES[exit_code][1]}: {_cause}\n{_cause.args}", file=sys.stderr)
return __EXIT_MSG # noqa


Expand Down
22 changes: 11 additions & 11 deletions multicast/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,12 +91,12 @@
from . import logging # skipcq: PLY-C0414
from . import socket # skipcq: PYL-C0414
import ipaddress
except Exception as err:
baton = ImportError(err, str("[CWE-758] Module failed completely."))
except ImportError as _cause:
baton = ImportError(_cause, "[CWE-758] Module failed completely.")
baton.module = __module__
baton.path = __file__
baton.__cause__ = err
raise baton from err
baton.__cause__ = _cause
raise baton from _cause


module_logger = logging.getLogger(__module__)
Expand Down Expand Up @@ -146,8 +146,8 @@ def validate_buffer_size(size: int) -> bool:
try:
size_num = int(size)
return 0 < size_num <= 65507
except (ValueError, TypeError) as err:
raise ValueError(f"Invalid buffer size value: {size}. Must be a positive integer.") from err
except (ValueError, TypeError) as _cause:
raise ValueError(f"Invalid buffer size value: {size}. Must be a positive integer.") from _cause


def validate_port(port: int) -> bool:
Expand Down Expand Up @@ -186,8 +186,8 @@ def validate_port(port: int) -> bool:
try:
port_num = int(port)
return 49152 <= port_num <= 65535
except (ValueError, TypeError) as err:
raise ValueError(f"Invalid port value: {port}. Must be an integer.") from err
except (ValueError, TypeError) as _cause:
raise ValueError(f"Invalid port value: {port}. Must be an integer.") from _cause


def validate_multicast_address(addr: str) -> bool:
Expand Down Expand Up @@ -248,10 +248,10 @@ def validate_ttl(ttl: int) -> bool:
try:
ttl_num = int(ttl)
return 1 <= ttl_num <= 126
except (ValueError, TypeError) as err:
except (ValueError, TypeError) as _cause:
raise ValueError(
f"Invalid TTL value: {ttl}. Must be a positive integer below 127."
) from err
f"Invalid TTL value: {ttl}. Must be a positive integer below 127.",
) from _cause


def load_buffer_size() -> int:
Expand Down
28 changes: 14 additions & 14 deletions multicast/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,12 @@
from . import argparse # skipcq: PYL-C0414
from . import logging # skipcq: PYL-C0414
import functools
except Exception as err:
baton = ImportError(err, str("[CWE-758] Module failed completely."))
except ImportError as _cause:
baton = ImportError(_cause, "[CWE-758] Module failed completely.")
baton.module = __module__
baton.path = __file__
baton.__cause__ = err
raise baton from err
baton.__cause__ = _cause
raise baton from _cause


module_logger = logging.getLogger(__module__)
Expand Down Expand Up @@ -581,8 +581,8 @@ def validate_exit_code(code) -> None:
try:
# Code that may raise an exception
pass
except Exception as e:
exit_code = get_exit_code_from_exception(e)
except Exception as _cause:
exit_code = get_exit_code_from_exception(_cause)
sys.exit(exit_code)
```

Expand Down Expand Up @@ -760,24 +760,24 @@ def wrapper(*args, **kwargs):
try:
_func_logger = logging.getLogger(func.__name__)
return func(*args, **kwargs)
except SystemExit as exc:
except SystemExit as baton:
# Handle SystemExit exceptions, possibly from argparse
exit_code = exc.code if isinstance(exc.code, int) else 2
exit_code = baton.code if isinstance(baton.code, int) else 2
_func_logger.warning(
"%s: %s", # lazy formatting to avoid PYL-W1203
EXIT_CODES[exit_code][1],
exc,
baton,
)
raise SystemExit(exit_code) from exc
raise SystemExit(exit_code) from baton
# otherwise sys.exit(exit_code)
except BaseException as err:
exit_code = get_exit_code_from_exception(err)
except BaseException as _cause:
exit_code = get_exit_code_from_exception(_cause)
_func_logger.warning(
"%s: %s", # lazy formatting to avoid PYL-W1203
EXIT_CODES[exit_code][1],
err,
_cause,
)
raise SystemExit(exit_code) from err
raise SystemExit(exit_code) from _cause
# otherwise sys.exit(exit_code)

return wrapper
Expand Down
Loading
Loading