Handling Server Errors in Streamlit: Capturing and Displaying Error Messages to Users

Hello everyone!

I received this error: AxiosError: Request failed with status code 413 for an application built in Streamlit. I noticed that the error is from the server, and I have increased the limit in nginx.

However, I would like to capture this error and display a message to the user saying that the file size is too large. I understand that the error is received from the server and rendered in Streamlit.

So how can I retrieve that specific error? Where does Streamlit handle server errors exactly? I hope you can help me.

Thank you very much!

Hi @Cosmin_Andrei

Thanks for your question.

Instead of capturing the error, here’s an implementation that conditionally display messages using if/else statement:

  1. If no file is uploaded a warning message is displayed via st.warning() to remind the user to upload a file
  2. If the file exceeds the 1 MB limit then it displays an error message via st.error()
  3. Else the success message is displayed via st.success()
import streamlit as st

MAX_FILE_SIZE = 1024 * 1024  # Maximum file size in bytes

uploaded_file = st.file_uploader("Choose a file")
if uploaded_file is not None and len(uploaded_file.read()) > MAX_FILE_SIZE:
    st.error("Error: File size is too large.")
elif uploaded_file is None:
    st.warning("Please upload a file!")
else:
    st.success('File successfully uploaded and processed.')

A screencast of the app is shown below:
ezgif.com-video-to-gif

Hope this helps!

Best regards,
Chanin

Thank you for the response and the idea. It could be a good approach that we will consider, but in this case, the file will be uploaded to the server, and I wanted to avoid uploading very large files. I will create a function that will delete any file in the end, but I’m trying to avoid their upload to the server. Maybe I didn’t fully explain in the first message. I looked closer now and realized that I could handle the issue differently. I could manipulate the st.file_uploader to have a limit of, for example, 20MB. I would need to add the following lines to the config.toml file in the .streamlit folder:

[server]
maxUploadSize = 20

More details can be found here - st.file_uploader - Streamlit Docs

Nevertheless, your solution is also welcome because it allows me to manage the messages that the user sees. Thank you very much!

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