翻篇收录说明
翻篇网页快照

Error Handling | AI SDK

https://ai-sdk.dev/docs/ai-sdk-ui/error-handling

最近抓取:2026-12-04 03:08:40(北京时间)

最近内容变化:2026-12-04 03:08:40(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Learn how to handle errors in the AI SDK UI

正文摘录

AI SDK UIMenuError HandlingCopy for LLMView MarkdownAsk AI about this pageWarnings The AI SDK shows warnings when something might not work as expected. These warnings help you fix problems before they cause errors. When Warnings Appear Warnings use Node.js process.emitWarning when available and console.warn in browser/edge runtimes. They appear when: Unsupported features: You use a feature or setting that is not supported by the AI model (e.g., certain options or parameters). Compatibility warnings: A feature is used in a compatibility mode, which might work differently or less optimally than intended. Deprecations: You use a deprecated API, option, or message format. Other warnings: The AI model reports another type of issue, such as general problems or advisory messages. Warning Messages All warnings include "AI SDK Warning" so you can easily find them. For example: AI SDK Warning: The feature "temperature" is not supported by this model Turning Off Warnings By default, warnings are shown in the console. You can control this behavior: Turn Off All Warnings Set a global variable to turn off warnings completely: globalThis.AI_SDK_LOG_WARNINGS = false; Custom Warning Handler You can also provide your own function to handle warnings. It receives a list of warnings and optional provider and model ids. Custom handlers receive every warning, including repeated deprecations. globalThis.AI_SDK_LOG_WARNINGS = ({ warnings, provider, model }) => { // Handle warnings your own way }; If your application loads multiple AI SDK versions in the same runtime, they all share globalThis.AI_SDK_LOG_WARNINGS. Each version calls the logger with its own arguments and warning types. The merged global type declarations prevent TypeScript declaration conflicts, but do not convert these arguments at runtime. A handler typed for only one version may therefore fail when another version calls it. Import LogWarningsFunction from every installed version that can call the logger and accept a union of their parameter types. For example, with AI SDK 7 installed as ai and AI SDK 6 installed under the package alias ai-v6 (npm:ai@6): import type { LogWarningsFunction as LogWarningsFunctionV7 } from 'ai'; import type { LogWarningsFunction as LogWarningsFunctionV6 } from 'ai-v6'; type LoggerOptions = | Parameters<LogWarningsFunctionV7>[0] | Parameters<LogWarningsFunctionV6>[0]; const logger = ({ warnings, provider, model }: LoggerOptions) => { for (const warning of warnings) { console.warn('AI SDK Warning:', warning, { provider, model }); } }; globalThis.AI_SDK_LOG_WARNINGS = logger; Check the argument shape and warning type before accessing version-specific fields. If AI SDK 5 is also installed, include its Experimental_LogWarningsFunction parameter type and use Array.isArray to handle its warning array before accessing the options object used by AI SDK 6 and 7. Per-Call Warning Handler You can pass onWarning to generateText, streamText, or ToolLoopAgent to handle the warnings of a single call, e.g. to show them in a terminal UI instead of writing them to stderr. When onWarning is set, the warnings of that call are not sent to the global warning logger. GatewayProviderCustomClaude Sonnet 5.5const result = streamText({ model: "anthropic/claude-sonnet-5.5", prompt: 'Hello, world!', onWarning: ({ warnings, provider, model }) => { // Show the warnings in your UI }, }); onWarning receives the warnings of each step, including prompt deprecations such as the legacy image content part. These are the same warnings as in step.warnings, result.warnings, and the start-step stream part. Deprecation Warnings The default logger emits each deprecation code once per loaded SDK instance. In Node.js, these warnings have the type DeprecationWarning and a stable AISDK_DEP_* code, available as warning.code on process.on('warning', handler). Browser/edge console messages include the code in brackets. CodeDeprecated usage / replacementAISDK_DEP_GENERATE_OBJECTUse generateText with output instead of generateObject.AISDK_DEP_STREAM_OBJECTUse streamText with output instead of streamObject.AISDK_DEP_EXPERIMENTAL_GENERATE_SPEECHUse generateSpeech instead of experimental_generateSpeech.AISDK_DEP_EXPERIMENTAL_TRANSCRIBEUse transcribe instead of experimental_transcribe.AISDK_DEP_EXPERIMENTAL_STREAM_TRANSCRIBEUse streamTranscription instead of experimental_streamTranscribe.AISDK_DEP_EXPERIMENTAL_STREAM_TRANSLATEUse streamSpeechTranslation instead of experimental_streamTranslate.AISDK_DEP_TOOL_RESULT_*Use file with tagged data instead of legacy tool-result content types.AISDK_DEP_UI_MESSAGE_RAW_INPUTUse input instead of rawInput in UI tool parts.AISDK_DEP_IMAGE_CONTENT_PARTUse file with an image mediaType instead of image message parts. Run Node.js with --throw-deprecation to fail on deprecated usage, --no-deprecation to suppress deprecations, or --trace-deprecation for stack traces. These flags affect all DeprecationWarnings, rather than individual codes, and apply only to the default Node.js logger. Error Handling Error Helper Object Each AI SDK UI hook also returns an error object that you can use to render the error in your UI. You can use the error object to show an error message, disable the submit button, or show a retry button. We recommend showing a generic error message to the user, such as "Something went wrong." This is a good practice to avoid leaking information from the server. app/page.tsx'use client'; import { useChat } from '@ai-sdk/react'; import { useState } from 'react'; export default function Chat() { const [input, setInput] = useState(''); const { messages, sendMessage, error, regenerate } = useChat(); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); sendMessage({ text: input }); setInput(''); }; return ( <div> {messages.map(m => ( <div key={m.id}> {m.role}:{' '} {m.parts .filter(part => part.type === 'text') .map(part => part.text) .join('')} </div> ))} {error && ( <> <div>An error occurred.</div> <button type="button" onClick={() => regenerate()}> Retry </button> </> )} <form onSubmit={handleSubmit}> <input value={input} onChange={e => setInput(e.target.value)} disabled={error != null} /> </form> </div> ); } Alternative: replace the failed message Alternatively, you can write a custom submit handler that replaces the failed user message with new input. If the assistant response started streaming before the error, remove both the partial assistant response and its user message. app/page.tsx'use client'; import { useChat } from '@ai-sdk/react'; import { useState } from 'react'; export default function Chat() { const [input, setInput] = useState(''); const { sendMessage, error, messages, setMessages } = useChat(); function customSubmit(event: React.FormEvent<HTMLFormElement>) { event.preventDefault(); if (error != null) { setMessages(messages => messages.at(-1)?.role === 'assistant' ? messages.slice(0, -2) : messages.slice(0, -1), ); } sendMessage({ text: input }); setInput(''); } return ( <div> {messages.map(m => ( <div key={m.id}> {m.role}:{' '} {m.parts .filter(part => part.type === 'text') .map(part => part.text) .join('')} </div> ))} {error && <div>An error occurred.</div>} <form onSubmit={customSubmit}> <input value={input} onChange={e => setInput(e.target.value)} /> </form> </div> ); } Error Handling Callback Errors can be processed by passing an onError callback function as an option to the useChat or useCompletion hooks. The callback function receives an error object as an argument. AI SDK-created client errors use exported error classes with marker-based .isInstance() guards: Error classAI SDK UI failureAPICallErrorA chat transport or completion request returns a non-successful HTTP response.EmptyResponseBodyErrorA successful chat transport or completion response has no body.UIMessageStreamErrorA completion data stream reports an error or a UI message stream contains invalid chunks.InvalidArgumentErrorAn invalid stream protocol or message ID is used.UnsupportedFunctionalityErrorA FileList is used in an environment that does not support it. Errors thrown by custom fetch implementations, callbacks, and stream parsers continue to propagate unchanged. app/page.tsximport { useChat } from '@ai-sdk/react'; import { APICallError, EmptyResponseBodyError } from 'ai'; export default function Page() { const { /* ... */ } = useChat({ // handle error: onError: error => { if (APICallError.isInstance(error)) { console.error('Request failed with status:', error.statusCode); } else if (EmptyResponseBodyError.isInstance(error)) { console.error('The server returned no response body.'); } else { console.error(error); } }, }); } For AI SDK UI requests, APICallError.requestBodyValues is undefined so prompts and messages are not copied into client-facing error objects. The response text remains available as message and responseBody; display a generic message to users to avoid leaking server information. Injecting Errors for Testing You might want to create errors for testing. You can easily do so by throwing an error in your route handler: app/api/chat/route.tsexport async function POST(req: Request) { throw new Error('This is a test error'); }PreviousStreaming Custom DataNextTransport