Is there a global on-exception hook?

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.

Made a feature request Request: hook for uncaught Exception · Issue #7690 · streamlit/streamlit · GitHub for this

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:


def main():
  st.write("This is my app!")
  # App code goes here
import myapp

except Exception as e:
  # Handle exception here

Then just run it like this:

$ streamlit run
1 Like

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.

1 Like

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

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.