KeyError happens after my service restarts while my user has the app open. This happens frequently as I push updates.
I’d like to catch this issue and automatically refresh the window. How do I catch this exception?
My app is multi-page with st.navigation, and I have this around my main function in my app_entry.py (file with st.navigation):
if __name__ == "__main__":
try:
main()
except KeyError as e:
logger.error(traceback.format_exc())
streamlit_js_eval(js_expressions="parent.window.location.reload()")
st.error(f"Frontend error! Try refreshing the page. Ask admin for help.")
But still it throws the KeyError without catching in the except KeyError block. Any way I can catch the KeyError?
Debugging info:
- Are you running your app locally or is it deployed? Deployed
- If your app is deployed:
a. Is it deployed on Community Cloud or another hosting platform? AWS ECS
b. Share the link to the public deployed app. It’s private - Share the link to your app’s public GitHub repository (including a requirements file). It’s private.
- Share the full text of the error message (not a screenshot).
KeyError: 'st.session_state has no key "$$WIDGET_ID-4dd4a76c5c949c58634579cb344294f6-questionnaire_select_box". Did you forget to initialize it? More info: https://docs.streamlit.io/develop/concepts/architecture/session-state#initialization'
Traceback:
File "/usr/local/lib/python3.12/site-packages/streamlit/runtime/scriptrunner/exec_code.py", line 88, in exec_func_with_error_handling
result = func()
^^^^^^
File "/usr/local/lib/python3.12/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 595, in code_to_exec
self._session_state.maybe_check_serializable()
File "/usr/local/lib/python3.12/site-packages/streamlit/runtime/state/safe_session_state.py", line 74, in maybe_check_serializable
self._state.maybe_check_serializable()
File "/usr/local/lib/python3.12/site-packages/streamlit/runtime/state/session_state.py", line 691, in maybe_check_serializable
self._check_serializable()
File "/usr/local/lib/python3.12/site-packages/streamlit/runtime/state/session_state.py", line 679, in _check_serializable
err_msg = f"""Cannot serialize the value (of type `{type(self[k])}`) of '{k}' in st.session_state.
~~~~^^^
File "/usr/local/lib/python3.12/site-packages/streamlit/runtime/state/session_state.py", line 412, in __getitem__
raise KeyError(_missing_key_error_message(key))
- Share the Streamlit and Python versions.
Streamlit 1.38.0, Python 3.12