Coverage for muutils/logger/exception_context.py: 50%
12 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-04-04 03:33 -0600
« prev ^ index » next coverage.py v7.6.1, created at 2025-04-04 03:33 -0600
1import json
3from muutils.json_serialize import json_serialize
6class ExceptionContext:
7 """context manager which catches all exceptions happening while the context is open, `.write()` the exception trace to the given stream, and then raises the exception
10 for example:
12 ```python
13 errorfile = open('error.log', 'w')
15 with ExceptionContext(errorfile):
16 # do something that might throw an exception
17 # if it does, the exception trace will be written to errorfile
18 # and then the exception will be raised
19 ```
21 """
23 def __init__(self, stream):
24 self.stream = stream
26 def __enter__(self):
27 return self
29 def __exit__(self, exc_type, exc_value, exc_traceback):
30 if exc_type is not None:
31 self.stream.write(
32 json.dumps(
33 json_serialize(
34 {
35 "exc_type": exc_type,
36 "exc_value": exc_value,
37 "exc_traceback": exc_traceback,
38 }
39 )
40 )
41 )
42 return False
43 return True