Frontend/React

React | λ Œλ”λ§ μ£ΌκΈ° - μ—λŸ¬ 처리 단계 (Error Handling)

이제희 2023. 12. 5. 17:00


μ—λŸ¬ 경계 (Error Boundary)

  • React μ• ν”Œλ¦¬μΌ€μ΄μ…˜μ—μ„œ μ»΄ν¬λ„ŒνŠΈ 트리 ν•˜μœ„μ—μ„œ λ°œμƒν•œ μ—λŸ¬λ₯Ό 처리 방법을 μ œκ³΅ν•˜λŠ” μ»΄ν¬λ„ŒνŠΈμ΄λ‹€.
  • μ• ν”Œλ¦¬μΌ€μ΄μ…˜μ˜ νŠΉμ • λΆ€λΆ„μ—μ„œ λ°œμƒν•œ μ—λŸ¬λ₯Ό λΆ€λͺ¨ μ»΄ν¬λ„ŒνŠΈμ—μ„œ μ²˜λ¦¬ν•  수 μžˆλ„λ‘ ν•œλ‹€.
  • μ• ν”Œλ¦¬μΌ€μ΄μ…˜ μ΅œμƒμœ„μ—μ„œ μ‚¬μš©λœλ‹€.
  • ν•„μš”μ— 따라 μ—¬λŸ¬ 개의 μ—λŸ¬ 경계λ₯Ό μ€‘μ²©ν•΄μ„œ μ‚¬μš©ν•  수 있으며, μ—¬λŸ¬ μ—λŸ¬λ₯Ό λ…λ¦½μ μœΌλ‘œ 처리 ν•  수 μžˆλ‹€.
  • μ• ν”Œλ¦¬μΌ€μ΄μ…˜ μΌλΆ€μ—μ„œ λ°œμƒν•œ μ—λŸ¬λ‘œ 전체 μ• ν”Œλ¦¬μΌ€μ΄μ…˜μ˜ λ Œλ”λ§μ΄ μ€‘λ‹¨λ˜λŠ” 것을 λ°©μ§€ ν•  수 μžˆλ‹€.

  • static getDerivedStateFromError()
    • μžμ‹ μ»΄ν¬λ„ŒνŠΈμ—μ„œ μ—λŸ¬κ°€ λ°œμƒν–ˆμ„ λ•Œ 호좜 λ˜λŠ” 정적 λ©”μ„œλ“œμ΄λ‹€.
    • μ—λŸ¬ μƒνƒœλ₯Ό μ»΄ν¬λ„ŒνŠΈμ— λ°˜μ˜ν•  수 μžˆλ‹€.
  • componentDidCatch()
    • 생λͺ…μ£ΌκΈ° λ©”μ„œλ“œ 쀑 ν•˜λ‚˜
    • μžμ‹ μ»΄ν¬λ„ŒνŠΈμ—μ„œ μ—λŸ¬κ°€ λ°œμƒν–ˆμ„ λ•Œ ν˜ΈμΆœλ˜λŠ” λ©”μ„œλ“œμ΄λ‹€.
    • μ—λŸ¬ 정보 μˆ˜μ§‘, λ‘œκΉ… λ“±μ˜ μž‘μ—…μ„ μˆ˜ν–‰ν•  수 μžˆλ‹€.

import React, { Component } from 'react';

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

  static getDerivedStateFromError(error) {
    // μ—λŸ¬κ°€ λ°œμƒν•˜λ©΄ μ—λŸ¬ μƒνƒœλ₯Ό μ—…λ°μ΄νŠΈ
    return {
      hasError: true,
      error: error,
    };
  }

  componentDidCatch(error, errorInfo) {
    // μ—λŸ¬ 정보λ₯Ό λ‘œκΉ…ν•˜κ±°λ‚˜ λ‹€λ₯Έ μž‘μ—…μ„ μˆ˜ν–‰
    console.error('Error caught by componentDidCatch:', error, errorInfo);
    this.setState({
      errorInfo: errorInfo,
    });
  }

  render() {
    if (this.state.hasError) {
      return (
        <div>
          <h1>Something went wrong!</h1>
          <p>{this.state.error && this.state.error.toString()}</p>
        </div>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
import React, { Component } from 'react';

class MyComponent extends Component {
  render() {
    // μ˜λ„μ μœΌλ‘œ μ—λŸ¬λ₯Ό λ°œμƒ
    throw new Error('This is an intentional error.');
    return <p>This component has an error.</p>;
  }
}

export default MyComponent;
import React, { Component } from 'react';
import ErrorBoundary from './ErrorBoundary';
import MyComponent from './MyComponent';

class App extends Component {
  render() {
    return (
      <ErrorBoundary>
        <MyComponent/>
      </ErrorBoundary>
    );
  }
}

export default App;

[ μ½”λ“œ μ‹€ν–‰ Result ]

  • MyComponentμ—μ„œ λ°œμƒν•œ μ—λŸ¬κ°€ ErrorBoundaryμ—μ„œ 처리 λœλ‹€.
  • ν™”λ©΄μ—λŠ” "Something went wrong!" κ³Ό ν•¨κ»˜ μ—λŸ¬ λ©”μ„Έμ§€κ°€ ν‘œμ‹œ λœλ‹€.
λ°˜μ‘ν˜•