Skip to content

Commit 276b9b7

Browse files
authored
Implemented multi-error handling in MultiError() class (#614)
* Implemented multi-error handling in MultiError() class * Added newsfragement file and test * updated doc-string and list-struct * updating docstring
1 parent 4b18607 commit 276b9b7

File tree

3 files changed

+53
-2
lines changed

3 files changed

+53
-2
lines changed

libp2p/exceptions.py

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
from collections.abc import (
2+
Sequence,
3+
)
4+
5+
16
class BaseLibp2pError(Exception):
27
pass
38

@@ -11,6 +16,38 @@ class ParseError(BaseLibp2pError):
1116

1217

1318
class MultiError(BaseLibp2pError):
14-
"""Raised with multiple exceptions."""
19+
r"""
20+
A combined error that wraps multiple exceptions into a single error object.
21+
This error is raised when multiple exceptions need to be reported together,
22+
typically in scenarios where parallel operations or multiple validations fail.
23+
24+
Example\:
25+
---------
26+
>>> from libp2p.exceptions import MultiError
27+
>>> errors = [
28+
... ValueError("Invalid input"),
29+
... TypeError("Wrong type"),
30+
... RuntimeError("Operation failed")
31+
... ]
32+
>>> multi_error = MultiError(errors)
33+
>>> print(multi_error)
34+
Error 1: Invalid input
35+
Error 2: Wrong type
36+
Error 3: Operation failed
37+
38+
Note\:
39+
------
40+
The string representation of this error will number and list all contained
41+
errors sequentially, making it easier to identify individual issues in
42+
complex error scenarios.
43+
44+
"""
45+
46+
def __init__(self, errors: Sequence[Exception]) -> None:
47+
super().__init__(errors)
48+
self.errors = errors # Storing list of errors
1549

16-
# todo: find some way for this to fancy-print all encapsulated errors
50+
def __str__(self) -> str:
51+
return "\n".join(
52+
f"Error {i + 1}: {error}" for i, error in enumerate(self.errors)
53+
)

newsfragments/613.feature.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Added support for multiple-error formatting in the `MultiError` class.

tests/exceptions/test_exceptions.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from libp2p.exceptions import (
2+
MultiError,
3+
)
4+
5+
6+
def test_multierror_str_and_storage():
7+
errors = [ValueError("bad value"), KeyError("missing key"), "custom error"]
8+
multi_error = MultiError(errors)
9+
# Check for storage
10+
assert multi_error.errors == errors
11+
# Check for representation
12+
expected = "Error 1: bad value\n" "Error 2: 'missing key'\n" "Error 3: custom error"
13+
assert str(multi_error) == expected

0 commit comments

Comments
 (0)