코딩 공부

React에서 Error Boundary로 에러 처리하기

새혀니 2024. 12. 20. 09:44

import React, { Component } from 'react';

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.error("Error Boundary caught an error:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h1>문제가 발생했습니다. 잠시 후 다시 시도해주세요.</h1>;
    }
    return this.props.children;
  }
}

function ProblematicComponent() {
  throw new Error('의도적으로 발생한 에러');
}

function App() {
  return (
    <ErrorBoundary>
      <h1>안전한 React 애플리케이션</h1>
      <ProblematicComponent />
    </ErrorBoundary>
  );
}

export default App;

 

 

Error Boundary로 앱의 신뢰성을 높이는 방법