문서
App Router 사용하기
unstableRethrow

unstable_rethrow

unstable_rethrow는 애플리케이션 코드에서 발생한 오류를 처리하려고 할 때 Next.js가 내부적으로 발생시킨 오류를 잡지 않도록 하는 데 사용할 수 있습니다.

예를 들어, notFound 함수를 호출하면 Next.js 내부 오류가 발생하고 not-found.js 컴포넌트가 렌더링됩니다. 그러나 try/catch 블록 내에서 사용되면 오류가 잡혀 not-found.js가 렌더링되지 않습니다:

@/app/ui/component.tsx
import { notFound } from "next/navigation";
 
export default async function Page() {
  try {
    const post = await fetch("https://.../posts/1").then((res) => {
      if (res.status === 404) notFound();
      if (!res.ok) throw new Error(res.statusText);
      return res.json();
    });
  } catch (err) {
    console.error(err);
  }
}

unstable_rethrow API를 사용하여 내부 오류를 다시 던지고 예상된 동작을 계속할 수 있습니다:

@/app/ui/component.tsx
import { notFound, unstable_rethrow } from "next/navigation";
 
export default async function Page() {
  try {
    const post = await fetch("https://.../posts/1").then((res) => {
      if (res.status === 404) notFound();
      if (!res.ok) throw new Error(res.statusText);
      return res.json();
    });
  } catch (err) {
    unstable_rethrow(err);
    console.error(err);
  }
}

다음 Next.js API들은 오류를 던지는 것에 의존하며, 이 오류들은 다시 던져져서 Next.js 자체에 의해 처리되어야 합니다:

라우트 세그먼트가 정적이 아닌 한 오류를 던지도록 표시된 경우, 동적 함수 호출도 개발자가 잡지 말아야 할 오류를 던집니다. 부분 사전 렌더링(PPR)도 이 동작에 영향을 미칩니다. 이러한 API들은 다음과 같습니다:

알아두면 좋은 점:

  • 이 메서드는 catch 블록의 맨 위에서 호출되어야 하며, 오류 객체를 유일한 인수로 전달해야 합니다. 프로미스의 .catch 핸들러 내에서도 사용할 수 있습니다.
  • 오류를 던지는 API 호출이 try/catch로 감싸져 있지 않도록 한다면 unstable_rethrow를 사용할 필요가 없습니다.
  • 리소스 정리(인터벌 해제, 타이머 해제 등)는 unstable_rethrow 호출 이전에 수행되거나 finally 블록 내에서 수행되어야 합니다.