Created
May 17, 2024 18:44
-
-
Save JacobFV/e236a3422b33b9a208fc49623694ee91 to your computer and use it in GitHub Desktop.
Collect all the errors in a block of code before raising
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import traceback | |
class DontRaiseUntilDone: | |
def __init__(self): | |
self.exceptions = [] | |
def __enter__(self): | |
return self | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
if exc_type: | |
self.exceptions.append((exc_type, exc_val, traceback.format_tb(exc_tb))) | |
return True # Suppress exception for now | |
def raise_exceptions(self): | |
if self.exceptions: | |
raise MultipleExceptions(self.exceptions) | |
class MultipleExceptions(Exception): | |
def __init__(self, exceptions): | |
self.exceptions = exceptions | |
def __str__(self): | |
return "\n".join( | |
f"Exception {i+1}:\nType: {exc_type.__name__}\nValue: {exc_val}\nTraceback: {''.join(tb)}" | |
for i, (exc_type, exc_val, tb) in enumerate(self.exceptions) | |
) | |
# Testing the context manager | |
try: | |
with DontRaiseUntilDone() as ctx: | |
try: | |
a = 1 / 0 | |
except Exception as e: | |
ctx.exceptions.append((type(e), e, traceback.format_exc())) | |
try: | |
b = [1, 2, 3] | |
c = b[5] | |
except Exception as e: | |
ctx.exceptions.append((type(e), e, traceback.format_exc())) | |
try: | |
d = int('not_a_number') | |
except Exception as e: | |
ctx.exceptions.append((type(e), e, traceback.format_exc())) | |
ctx.raise_exceptions() | |
except MultipleExceptions as e: | |
output = str(e) | |
print(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment