Files
2nd/10_Wiki/Topic_Programming/Frontend/Error Boundaries.md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
2026-07-05 00:33:48 +09:00

215 lines
6.1 KiB
Markdown

---
id: wiki-2026-0508-error-boundaries
title: Error Boundaries
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [React Error Boundary, ErrorBoundary, getDerivedStateFromError]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [react, error-handling, frontend, resilience]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: TypeScript
framework: React
---
# Error Boundaries
## 매 한 줄
> **"매 React subtree 의 의 render-time error 의 catch 의 의 fallback UI 의 의 swap 의 component"**. 의 entire app crash 의 의 prevent 의 — 의 try/catch 의 declarative React equivalent. 2026 의 의 매 React 19 의 still 의 class component 의만 의 의 Error Boundary 의 author 의 가능 (의 hook API 의 X).
## 매 핵심
### 매 catch 의 X 의 것
- Event handler error (의 try/catch 의 사용).
- Async code (setTimeout, promise) — Error Boundary 의 의 reach 의 X.
- SSR (의 server-side throw 의 의 catch 의 의 X).
- Boundary itself 의 throw.
### 매 catch 의 것
- 의 child render error.
- 의 lifecycle method error.
- 의 constructor error.
### 매 hierarchy strategy
- **Top-level**: 의 fallback "Something went wrong" 의 의 entire app crash 의 의 prevent.
- **Route-level**: 의 broken page 의만 의 의 fail.
- **Widget-level**: 의 chart, embed, third-party 의 의 isolate.
### 매 응용
1. Production crash 의 reporting (Sentry, Datadog).
2. Third-party widget 의 isolation.
3. Per-route error UI (Next.js `error.tsx`).
4. Suspense fallback combo (loading + error).
## 💻 패턴
### 기본 class boundary
```tsx
import { Component, type ReactNode, type ErrorInfo } from "react";
type Props = { fallback: ReactNode; onError?: (e: Error, info: ErrorInfo) => void; children: ReactNode };
type State = { hasError: boolean };
export class ErrorBoundary extends Component<Props, State> {
state: State = { hasError: false };
static getDerivedStateFromError(): State {
return { hasError: true };
}
componentDidCatch(error: Error, info: ErrorInfo) {
this.props.onError?.(error, info);
}
render() {
return this.state.hasError ? this.props.fallback : this.props.children;
}
}
```
### react-error-boundary 라이브러리
```tsx
import { ErrorBoundary } from "react-error-boundary";
function Fallback({ error, resetErrorBoundary }: { error: Error; resetErrorBoundary: () => void }) {
return (
<div role="alert">
<p>Something went wrong:</p>
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Retry</button>
</div>
);
}
<ErrorBoundary
FallbackComponent={Fallback}
onError={(error, info) => Sentry.captureException(error, { extra: info })}
onReset={() => queryClient.resetQueries()}
>
<Dashboard />
</ErrorBoundary>
```
### Suspense + ErrorBoundary 의 combo
```tsx
<ErrorBoundary FallbackComponent={Fallback}>
<Suspense fallback={<Skeleton />}>
<UserProfile id={userId} />
</Suspense>
</ErrorBoundary>
```
### 의 async event 의 의 manual rethrow
```tsx
function useAsyncError() {
const [, setState] = useState();
return useCallback((e: unknown) => {
setState(() => { throw e; });
}, []);
}
function MyComponent() {
const throwAsync = useAsyncError();
const onClick = async () => {
try {
await fetchData();
} catch (e) {
throwAsync(e); // 매 ErrorBoundary 의 의 reach
}
};
return <button onClick={onClick}>Load</button>;
}
```
### Next.js App Router `error.tsx`
```tsx
"use client";
export default function Error({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
useEffect(() => { console.error(error); }, [error]);
return (
<div>
<h2>Something went wrong</h2>
<button onClick={reset}>Retry</button>
</div>
);
}
```
### Per-route boundary
```tsx
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={
<ErrorBoundary FallbackComponent={HomeFailed}><Home /></ErrorBoundary>
} />
<Route path="dashboard" element={
<ErrorBoundary FallbackComponent={DashFailed}><Dashboard /></ErrorBoundary>
} />
</Route>
</Routes>
```
### 의 Sentry 의 integrate
```tsx
import * as Sentry from "@sentry/react";
const SentryBoundary = Sentry.withErrorBoundary(MyApp, {
fallback: ({ error, resetError }) => <Fallback error={error} resetErrorBoundary={resetError} />,
showDialog: true,
});
```
### Reset on prop change
```tsx
<ErrorBoundary
FallbackComponent={Fallback}
resetKeys={[userId]} // 의 userId 의 의 change 의 시 의 boundary reset
>
<UserProfile id={userId} />
</ErrorBoundary>
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Top-level app crash 의 prevent | Single root boundary + telemetry |
| Route 의 isolation | Per-route boundary (Next.js `error.tsx`) |
| Third-party widget | Tight boundary 의 의 widget 의만 |
| Async data fetch | TanStack Query 의 `throwOnError` + boundary |
| Form validation | Inline error UI — 매 boundary 의 X |
**기본값**: root + per-route + per-widget — 매 layered boundaries.
## 🔗 Graph
- 부모: [[React]] · [[Error Handling]]
- 변형: [[Suspense]] · [[React Error Boundary 패턴]]
- Adjacent: [[Discriminated Unions for Error Handling]]
## 🤖 LLM 활용
**언제**: production crash protection, third-party widget isolation, Suspense + error 의 combo.
**언제 X**: form-level validation — 매 inline UI 의 더 적합.
## ❌ 안티패턴
- **No top-level boundary**: 의 single child throw 의 의 entire app white-screen.
- **Boundary over async without rethrow**: 의 catch 의 의 fail — 의 manual rethrow 의 필요.
- **Eat error silently**: 매 telemetry 의 의 X — debug 의 impossible.
- **Reset 의 의 X**: user 의 의 retry 의 의 way 의 X — stuck 의 fallback.
- **getDerivedStateFromError 의 의 side effect**: pure function 의 의 의 violation.
## 🧪 검증 / 중복
- Verified (React 19 docs, react-error-boundary, Next.js App Router error handling, Sentry React SDK).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — async rethrow + Next.js error.tsx + reset key 추가 |