Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/helveg/errr
Elegantly create detailed exceptions in Python
https://github.com/helveg/errr
Last synced: 22 days ago
JSON representation
Elegantly create detailed exceptions in Python
- Host: GitHub
- URL: https://github.com/helveg/errr
- Owner: Helveg
- License: mit
- Created: 2020-09-04T16:45:28.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2022-05-31T12:45:50.000Z (over 2 years ago)
- Last Synced: 2024-12-10T19:17:19.540Z (about 2 months ago)
- Language: Python
- Size: 19.5 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# errr
Elegantly create detailed exceptions in Python.## Detailed exceptions
```python
>>> import errr
>>> class MyException(errr.DetailedException, list_detailts=True, details=["cause", "type"]):
... pass
...
>>> example = MyException("The backend server crashed", "backend", "crash")
>>> raise example
__main__.MyException: The backend server crashedDetails:
˪cause: backend
˪type: crash
>>> example.details
{'cause': 'backend', 'type': 'crash'}
>>> example.cause
'backend'
```## Semantic exceptions
You can also rapidly create large semantic trees of exceptions using the `make_tree`
function, listing exceptions as keyword arguments using the `errr.exception` factory
method. The `make_tree` method executes these recursive factories to produce your
exceptions. Nesting these factory methods will make the resultant exceptions inherit from
eachother. All of the produced exceptions are then flat injected into the given module
dictionary (typically) this should be `globals()` but you can inject into other modules
using `sys.modules["name"].__dict__`.```python
from errr import make_tree, exception as _emake_tree(
# Pass the module dictionary as first argument
globals(),
# List your nested exceptions
RootException=_e(
ChildException=_e(),
Child2Exception=_e()
),
SecondRootException=_e(
# List details as positional arguments
"detail1", "detail2",
# And continue with child exceptions as keyword arguments
AnotherChildException=_e()
)
)print(RootException)
#
print(ChildException)
#
print(ChildException.__bases__)
# (,)
```## Exception wrapping
You can catch and reraise exceptions as a new type of exception with the `wrap` function:
```python
import errrclass LibraryError(errr.DetailedException, details=["library"]):
passfor name, library in libraries.items():
try:
library.load()
except Exception as e:
errr.wrap(LibraryError, e, name, prepend="When trying to load %library% it reported:\n")
# Traceback
# ...
# __main__.LibraryError: When trying to load myLibrary it reported:
# Module 'missing' not found.
```