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

1from __future__ import annotations 

2 

3import json 

4from types import TracebackType 

5from typing import Protocol 

6 

7from muutils.json_serialize import json_serialize 

8 

9 

10class WritableStream(Protocol): 

11 """Protocol for objects that support write operations.""" 

12 

13 def write(self, __s: str) -> int: ... 

14 

15 

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 

18 

19 

20 for example: 

21 

22 ```python 

23 errorfile = open('error.log', 'w') 

24 

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 ``` 

30 

31 """ 

32 

33 def __init__(self, stream: WritableStream) -> None: 

34 self.stream: WritableStream = stream 

35 

36 def __enter__(self) -> ExceptionContext: 

37 return self 

38 

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