Skip to content

Instantly share code, notes, and snippets.

@francoiscampbell
Created November 3, 2021 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save francoiscampbell/f9084b19ba7019296dc983d384a2645c to your computer and use it in GitHub Desktop.
Save francoiscampbell/f9084b19ba7019296dc983d384a2645c to your computer and use it in GitHub Desktop.
Python safety
class Safety:
"""Context manager that catches and reports all exceptions.
Use this to catch and report exceptions around non-critical
code.
"""
def __init__(self, reporter=None):
"""
:param reporter A function that gets called with
(exc_type, exc_value, traceback). Use this to send
exceptions to Sentry, Rollbar, etc.
"""
self.reporter = reporter
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
if callable(self.reporter):
self.reporter(exc_type, exc_value, traceback)
return True
async def __aenter__(self):
pass
async def __aexit__(self, exc_type, exc_value, traceback):
if callable(self.reporter):
self.reporter(exc_type, exc_value, traceback)
return True
safety = Safety()
@francoiscampbell
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment