I am using Python 3.11 with Streamlit 1.28.1.
Is there some way to globally handle Exceptions?
I am looking for a hook I can use to ensure that any front-end Exceptions get logged, which for me will send them to Papertrail.
Streamlit handles exceptions before they hit sys.excepthook, so that’s not a viable route.
import sys
import streamlit as st
def excepthook(exctype, value, traceback) -> None:
print("excepthook called")
sys.__excepthook__(exctype, value, traceback)
sys.excepthook = excepthook
if st.button("BLOW UP"):
raise ValueError("BOOM")
This is due to handle_uncaught_app_exception handling Exceptions.
thiago
3
There’s no hook at the moment. For now, you just have to handle it as with any other Python script: wrap it in a try/except.
Personally, the way I’d do this would be to pull the app into a function, and then call it inside a try block:
# myapp.py
def main():
st.write("This is my app!")
# App code goes here
# streamlit_app.py
import myapp
try:
myapp.main()
except Exception as e:
# Handle exception here
Then just run it like this:
$ streamlit run streamlit_app.py
thiago
4
By the way, we are considering a hook system which would, among other things, open up this use-case. But that’s a few months away, at the earliest.
Sounds good, appreciate the follow up.
Also, thanks for sharing a different workaround in Code snippet: set up a custom exception handler for uncaught exceptions