Skip to content

Commit

Permalink
[Python] Store original PyChipError in ChipStackException
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
agners committed Jun 17, 2024
1 parent b3548dc commit 66ad50d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
24 changes: 21 additions & 3 deletions src/controller/python/chip/exceptions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
# limitations under the License.
#

from __future__ import annotations

__all__ = [
"ChipStackException",
"ChipStackError",
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/controller/python/chip/native/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 66ad50d

Please sign in to comment.