How to handle import error with streamlit in python

I am trying to print custom error message on the UI using streamlit if in case of import error.

Here is a simple code:

import streamlit as st
try:
    from google.auth import default
    from google.cloud import bigquery
except ImportError:
    st.write("Reauthentication is needed.")
    st.stop()


import pandas as pd
import base64



st.set_page_config(layout="wide")
pd.set_option('display.max_columns', None)
credentials, project_id = default()
client = bigquery.Client(credentials=credentials, project="project")
st.title('Tool')
st.write('Provide the ID')
_options = ['1', '2', '3']
default_client = "1"

with st.sidebar:
    _id = st.text_input("ID:","jhjkdkjhhkjhkj")

There is error in line from google.auth import default but when I launch streamlit using streamlit run app.py it runs the entire code and throws the Traceback in the UI.

How can I make sure the streamlit app stops as soon as its sees error without running the scanning the whole app.py and displays custom error message on the UI?

Hey @piam,

There isn’t a built-in way to display custom error messages, but there is a config option that allows you to limit the amount of details displayed in the error messages. If you set showErrorDetails = false in your config.toml file, deprecation warnings and full exception messages will print to the console only, and exceptions will display in the browser with a generic error message.

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