React
Error Boundary란 무엇일까?
shuai
2025. 2. 6. 15:44
https://ko.legacy.reactjs.org/docs/error-boundaries.html
에러 경계라는 새로운 개념에 대해 알게 되었다. 신기한 개념이라 정리해보았다.
개념
Error Boundaries라는게 뭘까? UI의 일부분에 존재하는 자바스크립트 에러가 전체 어플리케이션을 중단시켜서는 안된다. 하지만 과거에는 컴포넌트 내부의 자바스크립트 에러를 정상적으로 처리할 수 있는 방법이 없었다. 이를 위해 React 16에서 에러 경계라는 새로운 개념이 도입되었다. 즉, 에러 경계는 하위 컴포넌트 트리의 어디에서든 자바스크립트 에러를 기록하며 깨진 컴포넌트 트리 대신 폴백 UI를 보여주는 React 컴포넌트이다.
구현 방법
import React, { Component } from "react";
// Error Boundary 컴포넌트 (각 자식 컴포넌트를 개별적으로 보호)
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
// 에러 감지 시 상태 변경
static getDerivedStateFromError(error) {
return { hasError: true };
}
// 실제 에러 정보와 에러 발생 위치(info)를 콘솔에 출력
componentDidCatch(error, info) {
console.error("Error caught in ErrorBoundary:", error, info);
}
// "다시 시도" 버튼 클릭 시 에러 상태 초기화
resetError = () => {
this.setState({ hasError: false });
};
render() {
if (this.state.hasError) {
return (
<div style={{ color: "red", textAlign: "center", padding: "20px" }}>
<h2>⚠️ 이 컴포넌트에서 오류 발생!</h2>
<button
onClick={this.resetError}
...
>
다시 시도
</button>
</div>
);
}
return this.props.children;
}
}
// 정상 작동하는 컴포넌트
const GoodComponent = () => {
return <div style={{ color: "green" }}>✅ 정상적인 컴포넌트</div>;
};
// ❌ 에러가 발생하는 컴포넌트 (다시 시도 시, 50% 확률로 정상 동작)
const BadComponent = () => {
const shouldThrowError = Math.random() > 0.5; // 50% 확률로 에러 발생
if (shouldThrowError) {
throw new Error("Something went wrong!");
}
return <div style={{ color: "blue" }}>🎉 다시 시도 성공!</div>;
};
// ✅ 부모 컴포넌트
const ParentComponent = () => {
return (
<div style={{ fontSize: "20px", fontFamily: "Arial", padding: "20px" }}>
<h1>부모 컴포넌트</h1>
<ErrorBoundary>
<GoodComponent />
</ErrorBoundary>
<ErrorBoundary>
<BadComponent />
</ErrorBoundary>
</div>
);
};
export default ParentComponent;

- 자식 컴포넌트 하나에서 에러가 나더라도 앱 전체에 영향을 주지 않음
Error Boundary가 없다면?
import React from "react";
// ✅ 정상 작동하는 컴포넌트
const GoodComponent = () => {
return <div style={{ color: "green" }}>✅ 정상적인 컴포넌트</div>;
};
// ❌ 에러가 발생하는 컴포넌트
const BadComponent = () => {
throw new Error("Something went wrong!");
};
// 부모 컴포넌트
const ParentComponent = () => {
return (
<div style={{ fontSize: "20px", fontFamily: "Arial", padding: "20px" }}>
<h1>부모 컴포넌트</h1>
<GoodComponent />
<BadComponent />
</div>
);
};
export default ParentComponent;
- GoodComponent는 정상적으로 렌더링됨
- 하지만 BadComponent가 에러 발생 → React 전체가 중단됨
- ParentComponent도 사라지고 화면에는 흰 화면(오류 페이지) 만 보이게 됨
- Uncaught Error: Something went wrong! 같은 에러 메시지가 출력됨
이벤트 핸들러는 어떨까?
에러 경계는 이벤트 핸들러 내부에서는 에러를 포착하지 않는다. render 메서드 및 생명주기 메서드와 달리 이벤트 핸들러는 렌더링 중에 발생하지 않기 때문이다.
이벤트 핸들러 내에서 에러를 잡아야 하는 경우에는 일반 자바스크립트의 try / catch 구문을 사용해야 한다.
이번 기회에 개념을 정리했으니, 나중에 디자인 시스템 개발이 끝나면 적용해봐야겠다.