---
title: "React에 error boundary를 추가하고 놓치는 오류까지 기록하기"
description: "React error boundary는 렌더링 중에 생긴 오류를 잡아 폴백을 보여 줘요. 클래스 작성법, error boundary가 놓치는 오류, 각 오류를 LogBrew로 보내는 방법을 React 19.3에서 직접 테스트해 정리했어요."
canonical: "https://logbrew.co/ko/guides/react-error-boundary"
last_updated: "2026-11-21"
---

# React에 error boundary를 추가하고 놓치는 오류까지 기록하기

React error boundary는 렌더링 중에 생긴 오류를 잡아 폴백을 보여 줘요. 클래스 작성법, error boundary가 놓치는 오류, 각 오류를 LogBrew로 보내는 방법을 React 19.3에서 직접 테스트해 정리했어요.

React 19.3.1, Vite 8.3.8, Chrome 156, @logbrew/react 0.1.6, @logbrew/sdk 0.1.47 및 logbrew CLI 0.1.96 환경에서 2026년 11월 21일에 테스트

글 [Furkan Erday](https://github.com/furkanerday). LogBrew 창업자 Furkan Erday. 매일 Claude Code와 Codex로 LogBrew를 만들어요.

Canonical: https://logbrew.co/ko/guides/react-error-boundary

## 폴백을 보여 주고 LogBrew에 도착하는 React 오류

| 오류가 던져진 위치 | 폴백 표시 | LogBrew 이슈 |
| --- | --- | --- |
| 렌더링, `LogBrewErrorBoundary` 안 | 예 | 예 |
| `useEffect`, boundary 안 | 예 | 예 |
| 렌더링, boundary 없음 | 아니요, 루트가 비어 있음 | 예, 루트 옵션으로 |
| `onClick` 핸들러 | 아니요 | 아니요 |
| 비동기 핸들러, `await` 뒤 | 아니요 | 아니요 |
| `captureReactError()`를 쓴 `onClick` | 아니요 | 예 |

React 19.3.1과 @logbrew/react 0.1.6을 쓴 Vite 프로덕션 빌드 1개에서 일으킨 오류 6개.

## error boundary 작성하기

### boundary를 클래스 컴포넌트로 작성하기

React에는 이 용도의 훅이 없어서 error boundary는 클래스로 작성해요. `getDerivedStateFromError`는 다음 렌더링에서 폴백으로 바꿔요. `componentDidCatch`는 오류와 `info.componentStack`을 받아요. 이 값은 오류를 던진 컴포넌트 위에 있는 컴포넌트 목록이에요.

```bash
import { Component } from "react";

export class ErrorBoundary extends Component {
  state = { error: null };

  static getDerivedStateFromError(error) {
    return { error };
  }

  componentDidCatch(error, info) {
    console.log("caught:", error.message);
    console.log("in:", info.componentStack.split("\n")[1].trim());
  }

  render() {
    if (this.state.error) return <p role="alert">Could not load the taps.</p>;
    return this.props.children;
  }
}
```

### 실패할 수 있는 페이지 영역 감싸기

`TapList`는 `taps`가 없을 때 `taps.map`을 읽어서 렌더링 중에 오류를 던져요. boundary는 `Could not load the taps.`를 보여 줬고, `Taproom` 제목은 그대로 남았어요. 개발 모드에서는 React가 `The above error occurred in the <TapList> component`와 함께 오류도 출력했어요.

```bash
// TapList.jsx
export function TapList({ taps }) {
  return <ul>{taps.map((tap) => <li key={tap}>{tap}</li>)}</ul>;
}

// App.jsx
import { ErrorBoundary } from "./ErrorBoundary.jsx";
import { TapList } from "./TapList.jsx";

export function App() {
  return (
    <main>
      <h1>Taproom</h1>
      <ErrorBoundary>
        <TapList />
      </ErrorBoundary>
    </main>
  );
}
```

출력

```text
caught: Cannot read properties of undefined (reading 'map')
in: at TapList (http://127.0.0.1:25174/guide/TapList.jsx:3:27)
```

### 이벤트 핸들러의 오류는 boundary를 건너뛰어요

React는 `onClick`을 렌더링 밖에서 호출해서, boundary는 오류를 받지 못했어요. 버튼은 페이지에 남았고, 브라우저는 잡히지 않은 오류를 출력했어요. `await` 뒤에서 난 오류도 마찬가지였어요.

```bash
export function PourButton() {
  return (
    <button onClick={() => { throw new Error("pour failed"); }}>Pour</button>
  );
}

// main.jsx
createRoot(document.getElementById("root")).render(
  <ErrorBoundary>
    <PourButton />
  </ErrorBoundary>
);
```

출력

```text
Uncaught Error: pour failed
    at onClick (http://127.0.0.1:25174/guide/PourButton.jsx:6:10)
```

### 핸들러 오류를 state로 boundary에 넘기기

핸들러에서 오류를 잡아 `setError`로 저장하고, 다음 렌더링에서 던지세요. 그러면 boundary가 폴백을 보여 주고 `componentDidCatch`에서 오류를 받아요.

```bash
import { useState } from "react";

export function SafePourButton() {
  const [error, setError] = useState(null);
  if (error) throw error;

  function pour() {
    try {
      throw new Error("pour failed");
    } catch (caught) {
      setError(caught);
    }
  }

  return <button onClick={pour}>Pour</button>;
}
```

출력

```text
caught: pour failed
in: at SafePourButton (http://127.0.0.1:25174/guide/SafePourButton.jsx:7:28)
```

### boundary가 없으면 React가 트리 전체를 지워요

어떤 boundary도 렌더링 오류를 잡지 못하면 React 19는 루트를 언마운트해요. `root` 요소가 비었고 제목도 사라졌어요. React는 오류와 함께 error boundary를 추가하라는 경고를 출력했어요.

```bash
import { createRoot } from "react-dom/client";
import { TapList } from "./TapList.jsx";

createRoot(document.getElementById("root")).render(
  <main>
    <h1>Taproom</h1>
    <TapList />
  </main>
);
```

출력

```text
Uncaught TypeError: Cannot read properties of undefined (reading 'map')
An error occurred in the <TapList> component. Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://react.dev/link/error-boundaries to learn more about error boundaries.
```

## React 오류를 LogBrew로 보내기

### 패키지 설치하기

`@logbrew/react`에는 provider, error boundary, 루트 옵션이 들어 있어요. LogBrew 프로젝트의 브라우저 키를 `clientKey`로 사용하세요.

```bash
npm install @logbrew/sdk @logbrew/react react
```

### 클라이언트와 transport 만들기

클라이언트는 `client.flush(transport)`를 호출할 때까지 이벤트를 큐에 쌓아 둬요. transport는 `{ statusCode }`를 반환해야 해요. 저희 transport가 `fetch` 응답을 그대로 반환했을 때는 flush가 `invalid transport response`로 실패했어요. `VITE_LOGBREW_ENDPOINT`는 `https://api.logbrew.co/v1/events`로 설정하세요. 저희는 로컬 LogBrew 서버로 보냈어요.

```bash
import { createLogBrewReactClient } from "@logbrew/react";

export const client = createLogBrewReactClient({
  clientKey: import.meta.env.VITE_LOGBREW_CLIENT_KEY
});

export const transport = {
  async send(apiKey, body) {
    const response = await fetch(import.meta.env.VITE_LOGBREW_ENDPOINT, {
      method: "POST",
      headers: {
        authorization: `Bearer ${apiKey}`,
        "content-type": "application/json",
      },
      body
    });
    return { statusCode: response.status };
  }
};

export function send() {
  return client
    .flush(transport)
    .then((result) => console.log("sent", JSON.stringify(result)));
}
```

### LogBrewErrorBoundary를 LogBrewProvider 안에 두기

`LogBrewErrorBoundary`는 `LogBrewProvider`에서 클라이언트를 가져와요. provider가 없으면 폴백은 보여 줬지만 아무것도 보내지 않았고, `onCaptureError`는 `captureReactError requires a client`를 받았어요. `onError`는 캡처가 끝난 뒤 실행되니 거기서 flush하세요.

```bash
import { LogBrewErrorBoundary, LogBrewProvider } from "@logbrew/react";
import { client, send } from "./logbrew.js";
import { TapList } from "./TapList.jsx";

export function App() {
  return (
    <LogBrewProvider client={client}>
      <LogBrewErrorBoundary
        fallback={({ error, resetError }) => (
          <div role="alert">
            <p>Could not load the taps: {error.message}</p>
            <button onClick={resetError}>Try Again</button>
          </div>
        )}
        onError={send}
      >
        <TapList />
      </LogBrewErrorBoundary>
    </LogBrewProvider>
  );
}
```

출력

```text
sent {"statusCode":200,"attempts":1,"batches":1}
```

### 어떤 boundary도 잡지 못한 오류 잡기

`createLogBrewReactRootOptions()`는 `createRoot`에 오류 콜백을 넘겨요. boundary 없이 난 렌더링 오류도 이걸로 기록됐어요. `LogBrewErrorBoundary`가 이미 보낸 오류는 건너뛰어서 각 오류는 1번만 도착해요.

```bash
import { createRoot } from "react-dom/client";
import { createLogBrewReactRootOptions } from "@logbrew/react";
import { client, send } from "./logbrew.js";
import { TapList } from "./TapList.jsx";

createRoot(
  document.getElementById("root"),
  createLogBrewReactRootOptions(client, { onUncaughtError: send })
).render(<TapList />);
```

출력

```text
sent {"statusCode":200,"attempts":1,"batches":1}
```

### 핸들러 오류는 captureReactError()로 보고하기

핸들러에서 난 오류는 boundary도 루트 콜백도 받지 못해요. 그러니 직접 잡아서 `captureReactError()`에 넘기세요. 넘긴 `metadata`는 이슈에 남아요.

```bash
import { captureReactError } from "@logbrew/react";
import { client, send } from "./logbrew.js";

export function PayButton() {
  async function pay() {
    try {
      await Promise.resolve();
      throw new Error("payment declined");
    } catch (error) {
      captureReactError(client, error, { metadata: { action: "pay" } });
      send();
    }
  }

  return <button onClick={pay}>Pay</button>;
}
```

출력

```text
sent {"statusCode":200,"attempts":1,"batches":1}
```

### 이슈 다시 읽기

읽기 키로 프로젝트를 읽었어요. boundary 안의 렌더링 오류와 boundary 없이 난 같은 오류는 둘 다 `TapList.jsx`에서 나와서, 발생 2회짜리 이슈 1개가 됐어요. 핸들러 오류는 별도 이슈가 됐어요.

```bash
logbrew issues --since 3h
```

출력

```text
Issues (2)
- 1613a62e-31a3-5045-a144-c9c593760bff unresolved error priority=medium React error: payment declined occurrences=1 users=unknown last_seen=2026-11-21T06:35:49.154Z service=unknown_service trace=2ca253b519dfa2866268889760e5f2a0 assignee=unassigned [unversioned / production]
- f9eb7448-fab2-5d52-82f3-592a3b680a08 unresolved error priority=medium React error: Cannot read properties of undefined (reading 'map') occurrences=2 users=unknown last_seen=2026-11-21T06:35:43.870Z service=unknown_service trace=225e883023acc9c768da676fedd8e2c1 assignee=unassigned [unversioned / production]
```

## 직접 테스트해 보니

React 19.3.1과 @logbrew/react 0.1.6으로 Vite 앱 1개를 만들고, 로컬 LogBrew 서버와 함께 Chrome에서 각 경우를 실행했어요. 위의 출력은 Vite 개발 서버에서 나온 거예요. 프로덕션 빌드에서도 같은 경우를 실행했고 결과는 같았어요.

boundary에 도달한 건 렌더링 중과 `useEffect` 안에서 난 오류뿐이었어요. `onClick` 안과 `await` 뒤에서 난 오류는 어떤 boundary에도, 루트 콜백에도 도달하지 않았어요. 이 오류를 보낸 건 `captureReactError()`뿐이었어요.

|  | `LogBrewErrorBoundary` | `onUncaughtError` |
| --- | --- | --- |
| boundary 안의 렌더링 오류 | 예 | 아니요 |
| boundary 없는 렌더링 오류 | 아니요 | 예 |
| 이벤트 핸들러의 오류 | 아니요 | 아니요 |

## boundary를 초기화하고 다시 시도하기

`LogBrewErrorBoundary`의 폴백은 `resetError`를 받고, 이 함수는 자식을 다시 렌더링해요. 자식이 다시 오류를 던지면 boundary는 폴백을 다시 보여 주고 이벤트를 1개 더 보내요.

그러니 다시 시도하기 전에 원인을 고치세요. 예를 들어 데이터를 다시 불러오세요. 저희 테스트에서는 데이터가 있을 때 다시 시도하면 목록이 렌더링됐어요.

|  | 폴백 표시 | 이벤트 전송 |
| --- | --- | --- |
| 첫 렌더링 오류 | 예 | 예 |
| `Try Again`, 자식이 다시 오류를 던짐 | 예 | 예 |
| `Try Again`, 자식이 렌더링됨 | 아니요 | 아니요 |

## LogBrew가 기록하는 내용

React 오류는 각각 `React error:`와 메시지를 제목으로 한 이슈가 돼요. boundary는 메커니즘 `react.error_boundary`를 `handled: true`로 기록해요. 루트 옵션은 `react.uncaught_error`를 `handled: false`로 기록해요.

LogBrew는 React 오류를 오류 타입과 첫 번째 스택 프레임의 파일로 묶어요. 저희 프로덕션 빌드에서는 `keg sensor offline`, `tap list not loaded`처럼 메시지가 다른 `Error` 이벤트 5개가 번들 파일 1개에서 나와 이슈 1개가 됐어요. 개발 모드에서는 컴포넌트마다 파일이 따로 있어서 이슈도 따로 남았어요.

- `LogBrewErrorBoundary`
  - `mechanism`: `react.error_boundary`
  - `handled`: `true`
  - 이슈: `React error: Cannot read properties of undefined (reading 'map')`
- `createLogBrewReactRootOptions()`
  - `mechanism`: `react.uncaught_error`
  - `handled`: `false`
  - 스택 프레임: 10
- `captureReactError()`
  - 이슈: `React error: payment declined`
  - `metadata.action`: `pay`
  - 그룹화 키: `react.error:Error:…/HandlerButton.jsx`

## 자주 묻는 질문

### React에서 error boundary는 뭔가요?

`getDerivedStateFromError`나 `componentDidCatch`가 있는 클래스 컴포넌트예요. 자식이 렌더링 중에 오류를 던지면 React는 boundary의 폴백을 보여 주고 페이지의 나머지는 유지해요.

### error boundary를 훅으로 작성할 수 있나요?

아니요. React에는 이 용도의 훅이 없어서 boundary는 클래스로 작성해요. 1번만 작성하거나 `LogBrewErrorBoundary`를 사용하고, 함수 컴포넌트를 감싸세요.

### error boundary가 오류를 잡지 못하는 이유는 뭔가요?

오류가 렌더링 밖에서 던져졌기 때문이에요. 주로 이벤트 핸들러 안이나 `await` 뒤예요. 그 자리에서 잡아 `captureReactError()`로 보고하거나, state에 저장했다가 렌더링 중에 던지세요.

### error boundary는 어디에 두면 좋나요?

데이터를 불러오는 목록처럼 따로 실패할 수 있는 페이지 영역마다 감싸세요. 그래야 페이지의 나머지가 계속 동작해요. 루트 근처에도 1개 두세요. 어떤 boundary도 잡지 못한 오류는 트리 전체를 지우기 때문이에요.

### error boundary의 오류는 어떻게 기록하나요?

`componentDidCatch`에서 보내거나, `LogBrewProvider` 안에서 `LogBrewErrorBoundary`를 사용하세요. 어떤 boundary도 잡지 못한 오류를 위해 `createRoot`에 `createLogBrewReactRootOptions()`를 추가하세요.

## React 오류를 컴포넌트 스택과 함께 확인하세요

LogBrew는 React 렌더링 오류를 각각 컴포넌트 스택과 함께 기록하고, 반복된 오류를 이슈 1개로 묶어요. 넉넉한 무료 요금제로 시작하세요. 카드 등록은 필요 없어요.

[무료로 시작](https://logbrew.co/ko)

## 출처

- [React docs, Catching rendering errors with an Error Boundary](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)
- [React docs, createRoot parameters](https://react.dev/reference/react-dom/client/createRoot#parameters)
- [reactjs/react.dev#8157](https://github.com/reactjs/react.dev/issues/8157)

## 에이전트, Python, Node.js, React 가이드 더 보기

- [Claude Code와 Codex에 MCP 서버 추가하기](https://logbrew.co/ko/guides/mcp-server-claude-code-codex)
- [Claude Code와 Codex에서 AGENTS.md 쓰기](https://logbrew.co/ko/guides/agents-md)
- [Claude overloaded 529 오류와 rate limit 429 오류 해결하기](https://logbrew.co/ko/guides/claude-overloaded-rate-limit-error)
- [Python logging을 올바른 로그 레벨과 예외 기록까지 설정하기](https://logbrew.co/ko/guides/python-logging)
- [필드로 검색할 수 있는 로그 포맷과 로그 레벨로 구조화 로깅하기](https://logbrew.co/ko/guides/structured-logging)
- [Node.js 로깅을 Pino나 Winston으로 오류 하나 놓치지 않게 설정하기](https://logbrew.co/ko/guides/node-logging)
- [Django 로깅을 설정하고 모든 500 오류의 트레이스백 남기기](https://logbrew.co/ko/guides/django-logging)
- [FastAPI 로깅을 설정하고 트레이스백을 잃지 않고 오류 처리하기](https://logbrew.co/ko/guides/fastapi-logging)
- [트레이스 ID와 스팬 ID 차이, 실제 traceparent 헤더로 해석하기](https://logbrew.co/ko/guides/trace-id)
- [Minified React error #418과 #185를 전체 메시지와 내 코드 줄로 해결하기](https://logbrew.co/ko/errors/minified-react-error)
- [오류, 로그, 트레이스, 메트릭, 릴리스 가이드](https://logbrew.co/ko/guides)
