Code snippet: set up a custom exception handler for uncaught exceptions

Here’s a hack for those of you who want to log exceptions in Sentry or similar:

import sys
script_runner = sys.modules["streamlit.script_runner"]

orig = script_runner.handle_uncaught_app_exception

def new_handler(e):
    print("DO WHATEVER HERE", e)  # 👈Modify this line 
    orig(e)

script_runner.handle_uncaught_app_exception = new_handler

Just make sure you run this before your script!

And as with any hack, there is no guarantee this is going to work forever. If you’d like to see this as an official feature please upvote here.

3 Likes

@thiago : Here is another way that would work:

def main():
  pass # application logic goes here

if __name__ == "__main__":
  try:
    main()
  except Exception as e:
    print("DO WHATEVER HERE", e)  # 👈Modify this line 
    raise e

Thanks @thiago,

I’m trying the integrate sentry at this moment. How would you run the script before the streamlit run app.py cli command? Above example changes the ’script_runner.handle_uncaught_app_exception function at runtime right?