Coverage for muutils / logger / exception_context.py: 62%
16 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-18 02:51 -0700
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-18 02:51 -0700
1from __future__ import annotations
3import json
4from types import TracebackType
5from typing import Protocol
7from muutils.json_serialize import json_serialize
10class WritableStream(Protocol):
11 """Protocol for objects that support write operations."""
13 def write(self, __s: str) -> int: ...
16class ExceptionContext:
17 """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
20 for example:
22 ```python
23 errorfile = open('error.log', 'w')
25 with ExceptionContext(errorfile):
26 # do something that might throw an exception
27 # if it does, the exception trace will be written to errorfile
28 # and then the exception will be raised
29 ```
31 """
33 def __init__(self, stream: WritableStream) -> None:
34 self.stream: WritableStream = stream
36 def __enter__(self) -> ExceptionContext:
37 return self
39 def __exit__(
40 self,
41 exc_type: type[BaseException] | None,
42 exc_value: BaseException | None,
43 exc_traceback: TracebackType | None,
44 ) -> bool:
45 if exc_type is not None:
46 self.stream.write(
47 json.dumps(
48 json_serialize(
49 {
50 "exc_type": exc_type,
51 "exc_value": exc_value,
52 "exc_traceback": exc_traceback,
53 }
54 )
55 )
56 )
57 return False
58 return True