Sub topic 9
Showing errors to the user with gr.Error
This chapter assumes you can build a gr.ChatInterface app, that you know the (message, history) function contract, and that you have seen the streaming and LLM chapters. You should also be comfortable with Python try/except. The examples use Gradio 5.x.
Why error handling needs a plan
A chat function runs on the server, but the person who sees a failure is in a browser. If your function raises an ordinary exception, the traceback goes to your terminal. The user usually sees a short generic "Error" toast, which is a small pop-up in the corner of the page. They can't tell whether they typed something wrong, the model is overloaded, or your API key has expired.
gr.Error lets you decide what the user reads. You raise it from your function with a message you wrote, and Gradio shows that message in a toast.
Raising gr.Error
gr.Error is an exception class. You raise it. You don't call it like a function.
import gradio as gr
MAX_CHARS = 500
def respond(message, history):
if not message.strip():
raise gr.Error("Please type a message first.")
if len(message) > MAX_CHARS:
raise gr.Error(
f"Your message has {len(message)} characters. The limit is {MAX_CHARS}.",
duration=8,
)
return f"You said: {message}"
demo = gr.ChatInterface(fn=respond, type="messages")
if __name__ == "__main__":
demo.launch()Run it and submit a message of only spaces. A toast appears with your text, and no reply is added.
The constructor takes these arguments:
message: the text shown to the user.duration: seconds before the toast disappears. The default is 10. PassNoneto keep it until the user closes it.visible: set toFalseto hide the toast. Gradio still treats the call as failed.title: the toast heading. It defaults to "Error". Recent 5.x releases support it, so check your installed version.print_exception: whether Gradio also prints the traceback in the server log. It defaults toTrue.
The message is for a person, so write it as plain advice. Say what went wrong and what the user can do next.
What happens to other exceptions
Gradio handles exceptions in two different ways:
| Raised in your function | What the user sees | What you see in the log |
|---|---|---|
| `gr.Error("...")` | Your message in an error toast | The traceback, unless `print_exception=False` |
| Any other exception, such as `KeyError` | A generic "Error" toast, with no details by default | The full traceback |
| Any other exception, with `launch(show_error=True)` | The exception text in the toast | The full traceback |
The default hides details on purpose. Exception text can contain file paths, request URLs, or fragments of a prompt, and you don't want to expose those to strangers. Use show_error=True only while developing. In production, convert known failures to gr.Error with safe messages and let unknown ones stay generic.
Warnings and info toasts
Two sibling functions show toasts without failing the request. You call them and then keep going:
gr.Warning("text")shows a yellow toast.gr.Info("text")shows a neutral toast.
import gradio as gr
def respond(message, history):
if len(history) > 20:
gr.Warning("This conversation is getting long. Replies may slow down.")
return f"You said: {message}"
gr.ChatInterface(fn=respond, type="messages").launch()Use a warning when the reply still arrives but something deserves attention. Use gr.Error when you can't produce a reply. A common mistake is to write gr.Warning(...) with raise, or gr.Error(...) without it. The first fails because gr.Warning is a function, not an exception. The second does nothing, because the exception is created and thrown away.
Mapping LLM failures to messages
LLM calls fail often, and for reasons the user can sometimes fix by waiting or retrying. The code below catches the exception types from the openai package and raises a gr.Error for each. It reuses the streaming function from the LLM chapter.
import logging
import gradio as gr
import openai
from openai import OpenAI
logger = logging.getLogger(__name__)
client = OpenAI(timeout=30) # reads OPENAI_API_KEY from the environment
def respond(message, history):
messages = [{"role": "system", "content": "You are a helpful assistant."}]
messages += [{"role": h["role"], "content": h["content"]} for h in history]
messages.append({"role": "user", "content": message})
try:
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
stream=True,
)
reply = ""
for chunk in stream:
if not chunk.choices:
continue
reply += chunk.choices[0].delta.content or ""
yield reply
except openai.AuthenticationError:
logger.exception("API key rejected")
raise gr.Error("The server's API key was rejected. Please tell the app owner.")
except openai.RateLimitError:
raise gr.Error("The model is receiving too many requests. Wait a few seconds and try again.")
except (openai.APIConnectionError, openai.APITimeoutError):
raise gr.Error("Could not reach the model service. Check your connection and try again.")
except openai.APIStatusError as exc:
logger.exception("Model returned status %s", exc.status_code)
raise gr.Error("The model service returned an error. Please try again later.")
except openai.OpenAIError:
logger.exception("Unexpected OpenAI error")
raise gr.Error("Something went wrong while generating a reply.")
demo = gr.ChatInterface(fn=respond, type="messages")
if __name__ == "__main__":
demo.launch()Four details matter here:
- Order of
exceptclauses. Python uses the first clause that matches.AuthenticationErrorandRateLimitErrorare subclasses ofAPIStatusError, andAPITimeoutErroris a subclass ofAPIConnectionError. Put the specific classes first and the general ones last. Otherwise the general clause swallows them. - Log the real error and show the safe one. The user sees a short message. You keep the detail in the server log with
logger.exception. Never put the raw exception text, request headers, or keys in thegr.Errormessage. - No
gr.Errorinside thetrybody. Here none of theexceptclauses catchgr.Error, so it would pass through. If you add a bareexcept Exception, it would catch your owngr.Errortoo. Re-raise it first withexcept gr.Error: raise. - The timeout.
OpenAI(timeout=30)makes a stalled request fail in 30 seconds withAPITimeoutError, which you can then report. Without a timeout, the user may wait a long time with no feedback.
Errors while streaming
When your function is a generator, an error can happen after some text has already been yielded. In the code above, a dropped connection halfway through the stream raises inside the for chunk in stream loop. Gradio then shows the toast. The partial text was already sent to the browser. Whether it stays in the chat window depends on your Gradio version and on how the interface handles failed events, so test this case instead of assuming. If you need a guaranteed result, catch the error yourself, yield the partial reply plus a note such as "(reply interrupted)", and then return normally. This is a good fit when partial text is still useful.
Where the error is raised
The same pattern works in gr.Blocks apps. Raise gr.Error inside any event handler, such as the add_user_message or bot_reply functions from the Blocks chapter. Gradio shows the toast for the failed event. If you chain steps with .then(), the later steps still run by default. If a later step depends on the earlier one succeeding, use .success() instead of .then(). That runs the next step only when the previous one finished without an error.
msg.submit(add_user_message, [msg, chatbot], [msg, chatbot]).success(
bot_reply, chatbot, chatbot
)The error path
Common mistakes
- Leaking internals. Writing
raise gr.Error(str(exc))sends exception text to every visitor. Use fixed messages. - Blaming the user for server faults. "Invalid input" is wrong for a rate limit. Say whether the user can fix the problem or should wait.
- Raising
gr.Errorfor normal outcomes. An empty search result is not a failure. Return a normal reply that says so. - Skipping validation until the model call. Check cheap conditions first, such as empty text or a message that is too long. This saves an API call and gives faster feedback.
- Retrying silently forever. A short retry for a transient failure can help. Keep the number of attempts small, and raise
gr.Errorwhen they run out.
Exercise
A user reports that every failed request shows only the word "Error", with no explanation. Your function currently lets openai.RateLimitError escape. What two changes make the user see "Too many requests, please wait and try again", and why should you not use launch(show_error=True) in production for this?
Show answer
Catch openai.RateLimitError in the chat function and raise gr.Error("Too many requests, please wait and try again."), and log the original exception with logger.exception so you keep the detail on the server. show_error=True puts the raw exception text into the toast for every visitor, which can expose internal details such as URLs or request data. A gr.Error with a fixed message gives the user useful advice without that exposure.
Exercise
In the OpenAI example, why must the except openai.AuthenticationError clause come before except openai.APIStatusError?
Show answer
AuthenticationError is a subclass of APIStatusError. Python runs the first matching except clause, so if the general clause came first it would catch the authentication failure and the specific message would never be shown.