Okay, let's ask it "What's the capital of France?", and it says:
Could not complete request. Please try again.
Where is this beautifully written error text coming from, I wonder?
Well, it comes from this onError callback inside api/chat.ts:
We have a "Could not complete request. Please try again." text here, and "An unknown error occurred" text here.
In the frontend we are destructuring the error property from useChat:
And down here we have our error message:
Notice how the error class always has a message property and so that's how we know what to render on the frontend.
Having this onError property on the createUIMessageStream itself is pretty convenient because it means that any errors inside here will bubble up to the createUIMessageStream and be caught here:
So you can think of this like a try-catch for everything that happens inside the execute function.
As further reading I recommend you read through these AI SDK errors and if you notice them being sourced up from your code, then you now know a way that you can handle them and make them pretty on the frontend.
Nice work, and I will see you in the next one.
onError(error) {if (RetryError.isInstance(error)) {return `Could not complete request. Please try again.`;}return 'An unknown error occurred';},
const { messages, sendMessage, error } = useChat({})
const stream = createUIMessageStream({execute: async ({ writer }) => {throw new RetryError({errors: [new Error("An error occurred")],message: "Maximum retries exceeded",reason: "maxRetriesExceeded",})},onError(error) {if (RetryError.isInstance(error)) {return `Could not complete request. Please try again.`}return "An unknown error occurred"},})
{error && (<div className="flex items-center gap-2 p-3 mb-4 text-red-300 bg-red-900/20 border border-red-500/30 rounded-lg"><AlertCircle className="size-5 flex-shrink-0" /><span>{error.message}</span></div>)}