Sub topic 9
Showing errors to the user with gr.Error
This chapter assumes you can write a (message, history) chat function, know how generators stream replies, and have connected an OpenAI-compatible client as in the earlier chapters. It covers how to turn failures into clear messages in the browser.
Why default errors are not enough
If your chat function raises an ordinary exception, Gradio logs the traceback in your terminal. The browser shows only a generic red "Error" toast, because Gradio hides internal details by default. Your user sees no cause and no advice. Showing the full traceback instead (launch(show_error=True)) leaks internals, so it suits debugging only.
gr.Error is the middle path. You raise it with a message you wrote, and Gradio shows exactly that text in the toast.
flowchart TDReplace nothing above; the diagram follows.
Raising gr.Error
gr.Error is an exception class. Raise it anywhere inside your function:
import gradio as gr
def respond(message, history):
if not message.strip():
raise gr.Error("Please type a message before sending.")
return f"You said: {message}"
gr.ChatInterface(fn=respond, type="messages").launch()The constructor also accepts duration (seconds the toast stays visible, None for until dismissed) and title (the toast heading, default "Error").
raise gr.Error("The model is busy. Try again in a minute.", duration=8, title="Service busy")Translating LLM failures
The most useful place for gr.Error is around the model call. Catch the client library's specific exceptions and map each to advice the user can act on. Chain with from exc so the original cause still appears in your logs.
import gradio as gr
import openai
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
def respond(message, history):
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:
reply += chunk.choices[0].delta.content or ""
yield reply
except openai.RateLimitError as exc:
raise gr.Error("Too many requests. Please wait and retry.") from exc
except openai.APIConnectionError as exc:
raise gr.Error("Could not reach the model service.") from exc
except openai.AuthenticationError as exc:
raise gr.Error("The server's API key is invalid. Contact the admin.") from exc
if __name__ == "__main__":
gr.ChatInterface(fn=respond, type="messages").launch()Note the try also covers the loop. With streaming, many errors surface mid-iteration, not at create().
Warnings and info messages
Not every problem should stop the request. gr.Warning and gr.Info are ordinary function calls, not exceptions. They show a toast and let your function continue.
import gradio as gr
def respond(message, history):
if len(history) > 40:
gr.Warning("This conversation is long. Replies may be slower.")
return f"You said: {message}"
gr.ChatInterface(fn=respond, type="messages").launch()Common mistakes
- Writing
gr.Error("...")withoutraise. This builds an object and does nothing. - Catching
Exceptionand exposingstr(exc). Error text can contain URLs, keys, or paths. - Catching
gr.Erroryourself in a broadexcept Exception, which swallows your own message. Put narrower handlers first or re-raise. - Raising after a long stream. The toast appears, but the partial reply may remain, so keep messages self-explanatory.
Exercise
Your chat function calls an LLM and sometimes hits a rate limit. How do you show the user "Too many requests, please retry" while keeping the original exception in your server logs?
Show answer
Catch the client's rate-limit exception (for example openai.RateLimitError) and use raise gr.Error("Too many requests, please retry.") from exc. The toast shows your message, and the chained from exc keeps the original traceback in the terminal.
Exercise
What is the difference between raise gr.Error("x") and gr.Warning("x")?
Show answer
raise gr.Error stops the function and shows an error toast. gr.Warning is a normal call that shows a warning toast while the function keeps running.