Skip to main content

Error Handling

Handling Regular Errors

Regular errors are thrown and can be handled using the try/catch block.
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';

try {
  const { text } = await generateText({
    model: openai('gpt-4'),
    prompt: 'Write a vegetarian lasagna recipe for 4 people.',
  });
} catch (error) {
  // handle error
}
See Error Types for more information on the different types of errors that may be thrown.

Handling Streaming Errors (Simple Streams)

When errors occur during streams that do not support error chunks, the error is thrown as a regular error. You can handle these errors using the try/catch block.
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';

try {
  const { textStream } = streamText({
    model: openai('gpt-4'),
    prompt: 'Write a vegetarian lasagna recipe for 4 people.',
  });

  for await (const textPart of textStream) {
    process.stdout.write(textPart);
  }
} catch (error) {
  // handle error
}

Handling Streaming Errors (Streaming with error Support)

Full streams support error parts. You can handle those parts similar to other parts. It is recommended to also add a try-catch block for errors that happen outside of the streaming.
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';

try {
  const { fullStream } = streamText({
    model: openai('gpt-4'),
    prompt: 'Write a vegetarian lasagna recipe for 4 people.',
  });

  for await (const part of fullStream) {
    switch (part.type) {
      // ... handle other part types

      case 'error': {
        const error = part.error;
        // handle error
        break;
      }

      case 'abort': {
        // handle stream abort
        break;
      }

      case 'tool-error': {
        const error = part.error;
        // handle error
        break;
      }
    }
  }
} catch (error) {
  // handle error
}

Handling Stream Aborts

When streams are aborted (e.g., via chat stop button), you may want to perform cleanup operations like updating stored messages in your UI. Use the onAbort callback to handle these cases. The onAbort callback is called when a stream is aborted via AbortSignal, but onFinish is not called. This ensures you can still update your UI state appropriately.
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';

const { textStream } = streamText({
  model: openai('gpt-4'),
  prompt: 'Write a vegetarian lasagna recipe for 4 people.',
  onAbort: ({ steps }) => {
    // Update stored messages or perform cleanup
    console.log('Stream aborted after', steps.length, 'steps');
  },
  onFinish: ({ steps, totalUsage }) => {
    // This is called on normal completion
    console.log('Stream completed normally');
  },
});

for await (const textPart of textStream) {
  process.stdout.write(textPart);
}
The onAbort callback receives:
  • steps: An array of all completed steps before the abort
You can also handle abort events directly in the stream:
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';

const { fullStream } = streamText({
  model: openai('gpt-4'),
  prompt: 'Write a vegetarian lasagna recipe for 4 people.',
});

for await (const chunk of fullStream) {
  switch (chunk.type) {
    case 'abort': {
      // Handle abort directly in stream
      console.log('Stream was aborted');
      break;
    }
    // ... handle other part types
  }
}

Common Error Types

The AI SDK provides several error types to help you handle different failure scenarios:

API Errors

  • APICallError: Thrown when an API call fails
  • InvalidResponseDataError: Thrown when the API response is invalid
  • EmptyResponseBodyError: Thrown when the API returns an empty response

Content Generation Errors

  • NoContentGeneratedError: Thrown when no content is generated
  • NoOutputGeneratedError: Thrown when no output is generated
  • NoImageGeneratedError: Thrown when no image is generated
  • NoSpeechGeneratedError: Thrown when no speech is generated
  • NoTranscriptGeneratedError: Thrown when no transcript is generated
  • NoVideoGeneratedError: Thrown when no video is generated

Tool Errors

  • NoSuchToolError: Thrown when a tool is not found
  • InvalidToolInputError: Thrown when tool input is invalid
  • MissingToolResultsError: Thrown when tool results are missing

Configuration Errors

  • LoadAPIKeyError: Thrown when loading an API key fails
  • NoSuchModelError: Thrown when a model is not found
  • UnsupportedFunctionalityError: Thrown when a feature is not supported

Validation Errors

  • TypeValidationError: Thrown when type validation fails
  • InvalidArgumentError: Thrown when an argument is invalid
You can use instanceof checks to handle specific error types:
import { generateText, NoContentGeneratedError } from 'ai';
import { openai } from '@ai-sdk/openai';

try {
  const { text } = await generateText({
    model: openai('gpt-4'),
    prompt: 'Hello',
  });
} catch (error) {
  if (NoContentGeneratedError.isInstance(error)) {
    console.error('No content was generated');
  } else {
    console.error('An unexpected error occurred');
  }
}