오류 처리

오류 처리 (Error Handling)

AI SDK RSC에서 발생할 수 있는 오류를 처리하는 방법을 다루는 문서예요. UI 스트리밍 오류와 값 스트리밍 오류를 각각 어떻게 다루는지 알려줘요.

출처: 문서

본문

경고: AI SDK RSC는 현재 실험 단계(experimental)예요. 프로덕션에서는 AI SDK UI 사용을 권장해요. RSC에서 UI로 마이그레이션하는 방법은 마이그레이션 가이드를 참고하세요.

RSC API를 사용할 때 두 가지 종류의 오류가 발생할 수 있어요: 사용자 인터페이스를 스트리밍할 때 발생하는 오류와 다른 값을 스트리밍할 때 발생하는 오류예요.

UI 오류 처리 (Handling UI Errors)

UI를 생성하는 동안 오류를 처리하려면 streamableUI 객체가 제공하는 error() 메서드를 사용하세요.

'use server';

import { createStreamableUI } from '@ai-sdk/rsc';

export async function getStreamedUI() {
  const ui = createStreamableUI();

  (async () => {
    ui.update(<div>loading</div>);
    const data = await fetchData();
    ui.done(<div>{data}</div>);
  })().catch(e => {
    ui.error(<div>Error: {e.message}</div>);
  });

  return ui.value;
}

이 메서드를 사용하면 스트림에서 발생하는 모든 오류를 잡아 관련 UI를 반환할 수 있어요. 클라이언트에서는 React Error Boundary를 사용해 스트리밍된 컴포넌트를 감싸서 추가 오류를 잡을 수도 있어요.

import { getStreamedUI } from '@/actions';
import { useState } from 'react';
import { ErrorBoundary } from './ErrorBoundary';

export default function Page() {
  const [streamedUI, setStreamedUI] = useState(null);

  return (
    <div>
      <button
        onClick={async () => {
          const newUI = await getStreamedUI();
          setStreamedUI(newUI);
        }}
      >
        What does the new UI look like?
      </button>
      <ErrorBoundary>{streamedUI}</ErrorBoundary>
    </div>
  );
}

다른 오류 처리 (Handling Other Errors)

스트리밍 중 발생하는 다른 오류를 처리하려면, 수신 측에서 실패 원인을 파악할 수 있도록 오류 객체를 반환하면 돼요.

'use server';

import { createStreamableValue } from '@ai-sdk/rsc';
import { fetchData, emptyData } from '../utils/data';

export const getStreamedData = async () => {
  const streamableData = createStreamableValue<string>(emptyData);

  (async () => {
    const data1 = await fetchData();
    streamableData.update(data1);

    const data2 = await fetchData();
    streamableData.update(data2);

    const data3 = await fetchData();
    streamableData.done(data3);
  })().catch(e => {
    streamableData.error(e);
  });

  return { data: streamableData.value };
};

더 알아보기 (Learn more)