[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,111 +2,194 @@
id: wiki-2026-0508-error-handling-and-stability
title: Error Handling and Stability
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [e1r2r3o4-h5a6-4n7d-l8i9-n0g1s2t3a4b5]
aliases: [Frontend Error Boundaries, Error Recovery]
duplicate_of: none
source_trust_level: A
confidence_score: 0.99
tags: [react, error-handling, stability, error-boundary, monitoring, resilience]
confidence_score: 0.9
verification_status: applied
tags: [errors, stability, observability, sentry]
raw_sources: []
last_reinforced: 2026-05-01
github_commit: wikification-error-handling
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: TypeScript
framework: React/Vue
---
# Frontend Error Handling & Application Stability
# Error Handling and Stability
## 📌 한 줄 통찰 (The Karpathy Summary)
> 프론트엔드 안정성은 모든 에러를 막는 것이 아니라, 발생한 에러가 전체 앱의 화이트 스크린으로 번지지 않도록 구획을 나누고(Error Boundary), 실시간 모니터링을 통해 빠르게 인지하고 복구하는 회복 탄력성(Resilience)에 있다.
## 한 줄
> **"매 frontend stability = error 의 isolation + telemetry + graceful degradation."**. 매 single uncaught error가 매 SPA 의 전체 white-screen 의 유발 — 매 ErrorBoundary, global handlers (`window.onerror`, `unhandledrejection`), 매 Sentry-class telemetry 가 필수. 매 2026의 트렌드는 React 19 ErrorBoundary + Sentry + Replay + AI-driven root-cause clustering.
## 📖 구조화된 지식 (Synthesized Content)
### 1. 계층적 에러 처리 전략
- **Error Boundaries**: React 컴포넌트 트리 상위에서 하위 컴포넌트의 런타임 에러를 캡처하여 사용자에게 대체 UI를 보여준다. 핵심 비즈니스 영역별로 안전장치를 배치한다.
- **Global Error Handling**: `window.onerror`, `unhandledrejection` 이벤트를 구독하여 예기치 못한 비동기 에러를 전역에서 캡처하고 서버로 전송한다.
- **Local Error Handling**: `try-catch` 블록과 API 요청 계층의 인터셉터를 활용하여 사용자에게 즉각적인 피드백을 제공한다.
## 매 핵심
### 2. 애플리케이션 안정성 확보
- **Fallback UI**: 에러 발생 시 단순히 앱을 중단시키는 대신, 새로고침 버튼이나 고객센터 연결 등 다음 행동을 유도하는 UI를 제공한다.
- **Graceful Degradation**: 일부 기능(예: 추천 목록)이 실패하더라도 핵심 기능(예: 결제)은 유지될 수 있도록 모듈 간 결합도를 낮춘다.
### 매 layers
- **Component**: React ErrorBoundary, Vue `errorCaptured`, Svelte `<svelte:boundary>`.
- **Async**: try/catch, Promise `.catch`, `unhandledrejection` listener.
- **Global**: `window.onerror`, `window.onunhandledrejection`.
- **Network**: fetch retry, circuit breaker, AbortController.
### 3. 모니터링 및 분석
- **Sentry 통합**: 에러 발생 시점의 사용자 세션, 기기 정보, 스택 트레이스를 수집하여 재현 및 수정을 용이하게 한다.
### 매 telemetry 기둥
- Capture (stack, breadcrumb, source map).
- Group (fingerprint, dedup).
- Alert (threshold, regression).
- Replay (Sentry / LogRocket — DOM reconstruction).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과도한 에러 무시**: 모든 에러를 묵묵히 처리하면 실제 심각한 논리 오류를 놓칠 수 있다. 로그 수집과 경고 알림(Alerting) 체계가 병행되어야 한다.
- **에러 바운더리의 한계**: 이벤트 핸들러나 비동기 코드 내부의 에러는 Error Boundary가 직접 캡처하지 못하므로 별도의 처리가 필요하다.
### 매 응용
1. SPA route-level boundary — 매 chunk load fail 의 reload prompt.
2. Form submission retry with exponential backoff.
3. Feature flag fallback when remote config unavailable.
4. Service Worker offline shell.
## 🔗 지식 연결 (Graph)
- **Parent**: 10_Wiki/Topics/Development
- **Related**: Frontend Governance & Observability, Sentry and LogRocket Integration
- **Raw Source**: 00_Raw/Error Handling, 00_Raw/Frontend Application Stability, 00_Raw/React 애플리케이션 예\354\231\270 \353\260\217 \354\227\220\353\237\254 \354\262\230\353\246\254
## 💻 패턴
## 💻 GitHub 동기화 자동화 워크플로우
1. Stage: git add .
2. Commit: `git commit -m "[P-Reinforce] Wikify Frontend Error Handling and Application Stability Standard"`
3. Push: `git push origin main`
### 1. React ErrorBoundary (class)
```typescript
import { Component, type ReactNode } from 'react';
## 🔗 지식 연결 (Graph)
### Related Concepts (Auto-Linked)
* [[2026-05-01]]
* [[Boundaries]]
* [[Error Boundaries]]
* [[Frontend]]
* [[Frontend_Governance_and_Observability]]
* [[Observability]]
* [[P-Reinforce]]
* [[React]]
* [[Resilience]]
interface State { error?: Error }
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
export class ErrorBoundary extends Component<{ fallback: ReactNode; children: ReactNode }, State> {
state: State = {};
static getDerivedStateFromError(error: Error): State { return { error }; }
componentDidCatch(error: Error, info: React.ErrorInfo) {
Sentry.captureException(error, { extra: { componentStack: info.componentStack } });
}
render() {
return this.state.error ? this.props.fallback : this.props.children;
}
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### 2. react-error-boundary (functional)
```typescript
import { ErrorBoundary } from 'react-error-boundary';
**선택 A를 써야 할 때:**
- *(TODO)*
<ErrorBoundary
fallbackRender={({ error, resetErrorBoundary }) => (
<div role="alert">
<p>Failed: {error.message}</p>
<button onClick={resetErrorBoundary}>Retry</button>
</div>
)}
onReset={() => location.reload()}
>
<App />
</ErrorBoundary>
```
**선택 B를 써야 할 때:**
- *(TODO)*
### 3. Global handlers
```typescript
window.addEventListener('error', (e) => {
Sentry.captureException(e.error ?? new Error(e.message));
});
window.addEventListener('unhandledrejection', (e) => {
Sentry.captureException(e.reason);
});
```
**기본값:**
> *(TODO)*
### 4. Chunk load failure recovery
```typescript
const lazyWithRetry = <T,>(load: () => Promise<{ default: T }>) =>
React.lazy(async () => {
try {
return await load();
} catch (err) {
if (!sessionStorage.getItem('chunk-retried')) {
sessionStorage.setItem('chunk-retried', '1');
location.reload();
}
throw err;
}
});
```
## ❌ 안티패턴 (Anti-Patterns)
### 5. Fetch retry with backoff
```typescript
async function fetchRetry(url: string, retries = 3, delay = 500): Promise<Response> {
try {
const res = await fetch(url);
if (!res.ok && res.status >= 500) throw new Error(`HTTP ${res.status}`);
return res;
} catch (err) {
if (retries === 0) throw err;
await new Promise((r) => setTimeout(r, delay));
return fetchRetry(url, retries - 1, delay * 2);
}
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### 6. AbortController on unmount
```typescript
useEffect(() => {
const ac = new AbortController();
fetch('/api/x', { signal: ac.signal }).catch((e) => {
if (e.name !== 'AbortError') report(e);
});
return () => ac.abort();
}, []);
```
### 7. Sentry init (2026)
```typescript
import * as Sentry from '@sentry/react';
Sentry.init({
dsn: import.meta.env.VITE_SENTRY_DSN,
integrations: [
Sentry.browserTracingIntegration(),
Sentry.replayIntegration({ maskAllText: false }),
],
tracesSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
release: import.meta.env.VITE_RELEASE,
});
```
### 8. Vue 3 errorHandler
```typescript
import { createApp } from 'vue';
const app = createApp(App);
app.config.errorHandler = (err, instance, info) => {
Sentry.captureException(err, { extra: { info } });
};
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Component-local fail | ErrorBoundary at route level. |
| Async fail | try/catch + telemetry. |
| Chunk 404 (deploy mid-session) | lazyWithRetry + reload. |
| Transient 5xx | Exponential backoff retry. |
| Auth expired | Refresh token interceptor. |
**기본값**: Sentry + Replay + per-route ErrorBoundary + global handlers.
## 🔗 Graph
- 부모: [[Observability]] · [[Web Reliability]]
- 변형: [[Server Error Handling]] · [[Circuit Breaker]]
- 응용: [[Sentry]] · [[Datadog RUM]] · [[Logrocket]]
- Adjacent: [[Source Maps]] · [[Feature Flags]]
## 🤖 LLM 활용
**언제**: ErrorBoundary scaffolding, retry helper 작성, Sentry config.
**언제 X**: 매 root-cause analysis from minified stack — 매 source map upload 필수.
## ❌ 안티패턴
- **Swallow errors**: 매 `catch {}` 빈 — 매 silent fail.
- **No source map**: 매 prod stack 의 `a.b.c` — 매 debug X.
- **Boundary at root only**: 매 한 component fail이 매 entire app crash.
- **Console.error as monitoring**: 매 user 의 console 의 도달 X — telemetry 필수.
## 🧪 검증 / 중복
- Verified (Sentry docs, react.dev error boundary).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Error boundary + Sentry 2026 patterns |