C.W.K.
Stream
Lesson 03 of 07 · published

Error boundary — 여전히 쓰는 유일한 클래스

~11 min · error-boundary, errors, fallback

Level 0React 입문자
0 XP0/54 lessons0/12 achievements
0/100 XP to next level100 XP to go0% complete
Error boundary 는 render 트리의 try/catch. Descendant 가 render 중에 throw 하면 가장 가까운 경계가 잡아서 fallback 보여줘. 2026년에 일부러 클래스 컴포넌트 쓰는 유일한 자리.

Error boundary 가 잡는 것

Error boundary 가 descendant 의 render 중 throw 된 에러 잡음. NOT 잡음:

  • 이벤트 핸들러 에러 (인라인 try/catch 로 처리).
  • setTimeout / render 에 surface 안 되는 promise rejection (출처에서 처리).
  • 경계 자신의 에러 (그건 부모 경계 필요).
  • 서버 사이드 render 에러 (경계 아니라 프레임워크가 처리).

Suspense 의 로딩 + use() 의 데이터와 결합해서 error boundary 가 loading/error/success 의 error 1/3 커버.

클래스 모양

Error boundary 는 getDerivedStateFromError (자식 throw 시 fallback state 설정) 와 componentDidCatch (에러를 reporting 서비스에 로그) 필요. 한 번 작성, 어디나 재사용.

react-error-boundary 라이브러리

npm 패키지 react-error-boundary 가 다듬은 버전 export: <ErrorBoundary FallbackComponent={...} onError={...}>. 그 외에 다른 방법으로는 경계에 안 닿을 async 코드 안에서 경계 트리거하는 useErrorBoundary 도 줘. 대부분 앱이 hand-roll 대신 이 라이브러리.

Reset 동작

경계가 에러 잡으면 뭔가 reset 할 때까지 에러 상태 유지. 라이브러리의 fallback 컴포넌트의 resetErrorBoundary prop 이 이거 처리 — 보통 '다시 시도' 버튼에 연결.

출하 가능한 모든 영역에 경계 하나. 거대한 경계 하나 안의 앱 전체 = 모든 에러에 crash 페이지. 주요 feature (sidebar, 메인 패널, settings 다이얼로그) 마다 경계 = feature 하나 fail 해도 UI 전체 blank 안 됨. 경계 granularity 를 surface-area outage 에 대한 본인 관용도에 매치.

Code

최소 hand-rolled error boundary 클래스·tsx
import { Component, type ReactNode } from "react";

type Props = {
  fallback: (error: Error, reset: () => void) => ReactNode;
  children: ReactNode;
};
type State = { error: Error | null };

export class ErrorBoundary extends Component<Props, State> {
  state: State = { error: null };

  static getDerivedStateFromError(error: Error): State {
    return { error };
  }

  componentDidCatch(error: Error, info: React.ErrorInfo) {
    // 본인 에러 트래커에 리포트.
    console.error("ErrorBoundary caught:", error, info);
  }

  reset = () => this.setState({ error: null });

  render() {
    if (this.state.error) {
      return this.props.fallback(this.state.error, this.reset);
    }
    return this.props.children;
  }
}
react-error-boundary — 다듬은 버전·tsx
import { ErrorBoundary } from "react-error-boundary";
import { Suspense } from "react";

function Fallback({ error, resetErrorBoundary }: { error: Error; resetErrorBoundary: () => void }) {
  return (
    <div role="alert" className="p-4 rounded-card bg-bg-elevated">
      <p className="text-danger font-medium">Something went wrong</p>
      <p className="text-muted text-sm mt-1">{error.message}</p>
      <button
        onClick={resetErrorBoundary}
        className="mt-3 px-3 py-1 rounded bg-brand text-bg"
      >
        Try again
      </button>
    </div>
  );
}

// Suspense 와 합성 — 경계는 Suspense OUTSIDE
// Suspense 안의 render 에러 잡으려고.
function App() {
  return (
    <ErrorBoundary FallbackComponent={Fallback}>
      <Suspense fallback={<p>Loading…</p>}>
        <Page />
      </Suspense>
    </ErrorBoundary>
  );
}

External links

Exercise

react-error-boundary 설치. Bootstrap 프로젝트 컨텐츠를 친근한 fallback 가진 ErrorBoundary 로 감싸. 일부러 render 에러 트리거 (throw new Error('test') 를 컴포넌트의 render 중에) 해서 fallback 보이는지 확인. Reset 버튼 연결 + 페이지가 정상 복귀하는지 확인. 보너스: onClick 핸들러 안에서 에러 트리거하고 경계가 NOT 잡는지 관찰 — 이벤트-핸들러 caveat 의 동작.
Hint
이벤트-핸들러 에러는 핸들러 안에서 useErrorBoundary().showBoundary(error) 로 경계에 forward 필요. 또는 로컬 에러 state 잡고 컴포넌트 자체에서 에러 UI 렌더.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.