Skip to main content

Error Handling

还没翻译译自英文(ai-sdk.dev)本页 35 段都还没译

Warnings

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.

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 / replacement
AISDK_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_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.

Note

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.

'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.

'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 failure
APICallErrorA 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.

import { 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:

export async function POST(req: Request) {
  throw new Error('This is a test error');
}