通常のエラーは (例外として) 投げられて try/catch ブロックを使用して処理できます。
Vercel AI SDK 6 : AI SDK Core – エラー処理
作成 : Masashi Okumura (@classcat.com)
作成日時 : 02/01/2026
バージョン : ai@6.0.64
* 本記事は ai-sdk.dev/docs の以下のページを参考にしています :
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
◆ お問合せ : 下記までお願いします。
- クラスキャット セールス・インフォメーション
- sales-info@classcat.com
- ClassCatJP

Vercel AI SDK 6.x : AI SDK Core – エラー処理
通常のエラーの処理
通常のエラーは (例外として) 投げられて try/catch ブロックを使用して処理できます。
Gateway
import { generateText } from 'ai';
try {
const { text } = await generateText({
model: "openai/gpt-4o-mini",
prompt: 'Write a vegetarian lasagna recipe for 4 people.',
});
} catch (error) {
// handle error
}
投げられる可能性のあるエラーの様々なタイプについての詳細は Error Types をご覧ください。
ストリーミングエラーの処理 (単純なストリーム)
エラーチャンクをサポートしていないストリームのでエラーは発生した場合、エラーは通常のエラーとして投げられます。try/catch ブロックを使用してこれらのエラーを処理できます。
Gateway
import { streamText } from 'ai';
try {
const { textStream } = streamText({
model: "openai/gpt-4o-mini",
prompt: 'Write a vegetarian lasagna recipe for 4 people.',
});
for await (const textPart of textStream) {
process.stdout.write(textPart);
}
} catch (error) {
// handle error
}
ストリーミングエラーの処理 (エラーサポートを備えたストリーミング)
フルストリームはエラー部分をサポートしています。他の部分と同様にこれらの部分を処理できます。ストリーミング外で発生したエラーに対しては try-catch ブロックを追加することも勧めます。
Gateway
import { streamText } from 'ai';
try {
const { fullStream } = streamText({
model: "openai/gpt-4o-mini",
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
}
ストリーミング中止 (abort) の処理
ストリーミングが中止された場合 (e.g., チャット停止ボタン経由)、UI 内でストアされたメッセージを更新するようなクリーンアップ操作を実行したい場合があります。これらのケースを処理するには onAbort コールバックを使用します。
onAbort コールバックは、AbortSignal でストリーミングが中止されたものの onFinish は呼び出されていないときに、呼び出されます。これは、UI 状態を適切に更新することを確実にします。
Gateway
import { streamText } from 'ai';
const { textStream } = streamText({
model: "openai/gpt-4o-mini",
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);
}
onAbort コールバックは以下を受信します :
- steps: 中止前に完了したすべてのステップの配列
ストリーム内で直接 abort イベントを処理することもできます :
Gateway
import { streamText } from 'ai';
const { fullStream } = streamText({
model: "openai/gpt-4o-mini",
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
}
}
以上
