From 66ad50d804bbbe2614a7cac8c538a048a00a56fa Mon Sep 17 00:00:00 2001 From: Stefan Agner Date: Mon, 17 Jun 2024 16:42:07 +0200 Subject: [PATCH] [Python] Store original PyChipError in ChipStackException This change stores the original PyChipError in ChipStackException so that details of the original error code can still be retrieved. This is interesting to use the properties returning processed information about the original error code. It also preserves the line and code file which can be helpful. --- .../python/chip/exceptions/__init__.py | 24 ++++++++++++++++--- src/controller/python/chip/native/__init__.py | 2 +- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/controller/python/chip/exceptions/__init__.py b/src/controller/python/chip/exceptions/__init__.py index 6b1969f1efe5c4..749a59fce647b8 100644 --- a/src/controller/python/chip/exceptions/__init__.py +++ b/src/controller/python/chip/exceptions/__init__.py @@ -15,6 +15,8 @@ # limitations under the License. # +from __future__ import annotations + __all__ = [ "ChipStackException", "ChipStackError", @@ -26,15 +28,31 @@ "UnknownCommand", ] +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from chip.native import PyChipError class ChipStackException(Exception): pass class ChipStackError(ChipStackException): - def __init__(self, err, msg=None): - self.err = err - self.msg = msg if msg else "Chip Stack Error %d" % err + def __init__(self, chip_error: PyChipError, msg=None): + self.chip_error = chip_error + self.msg = msg if msg else "Chip Stack Error %d" % chip_error.code + + @classmethod + def from_chip_error(cls, chip_error: PyChipError) -> ChipStackError: + return cls(chip_error, str(chip_error)) + + @property + def chip_error(self) -> PyChipError | None: + return self.chip_error + + @property + def err(self) -> int: + return self.chip_error.code def __str__(self): return self.msg diff --git a/src/controller/python/chip/native/__init__.py b/src/controller/python/chip/native/__init__.py index 26295c2011a26b..9ee94c61ddaa7f 100644 --- a/src/controller/python/chip/native/__init__.py +++ b/src/controller/python/chip/native/__init__.py @@ -116,7 +116,7 @@ def sdk_code(self) -> int: def to_exception(self) -> typing.Union[None, chip.exceptions.ChipStackError]: if not self.is_success: - return chip.exceptions.ChipStackError(self.code, str(self)) + return chip.exceptions.ChipStackError.from_chip_error(self) def __str__(self): buf = ctypes.create_string_buffer(256)