React Error Boundary

λŸ°νƒ€μž„μ—μ„œ μ»΄ν¬λ„ŒνŠΈ λ‚΄μ˜ μžλ°”μŠ€ν¬λ¦½νŠΈ 였λ₯˜λŠ” React 앱을 μ†μƒμ‹œν‚€κ³  전체 앱이 μ€‘λ‹¨λ˜λŠ” 문제점이 쑴재

React 16μ—μ„œλŠ” μ΄λŸ¬ν•œ μžλ°”μŠ€ν¬λ¦½νŠΈ 였λ₯˜λ₯Ό μ μ ˆν•˜κ²Œ μ²˜λ¦¬ν•˜κΈ° μœ„ν•΄ 였λ₯˜ 경계λ₯Ό λ„μž…

였λ₯˜ 경계 μ†Œκ°œ

였λ₯˜ κ²½κ³„λŠ” ν•˜μœ„μ˜ ꡬ성 μš”μ†Œ 트리 μ–΄λ””μ„œλ“  μžλ°”μŠ€ν¬λ¦½νŠΈ 였λ₯˜λ₯Ό ν¬μ°©ν•˜κ³  ν•΄λ‹Ή 였λ₯˜λ₯Ό 기둝, 좩돌이 λ°œμƒν•œ κ΅¬μ„±μš”μ†Œ λŒ€μ‹  λŒ€μ²΄ UI(fallback)λ₯Ό ν‘œμ‹œ

  • 였λ₯˜ κ²½κ³„μ—μ„œ componentDidCatch() λ©”μ„œλ“œλŠ” ꡬ성 μš”μ†Œμ— λŒ€ν•΄ μžλ°”μŠ€ν¬λ¦½νŠΈμ˜ catch {} 문처럼 μž‘λ™

  • 였λ₯˜ κ²½κ³„λŠ” νŠΈλ¦¬μ—μ„œ ν•˜μœ„ ꡬ성 μš”μ†Œμ˜ 였λ₯˜λ§Œ 포착

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

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    // Example "componentStack":
    //   in ComponentThatThrows (created by App)
    //   in ErrorBoundary (created by App)
    //   in div (created by App)
    //   in App
    logErrorToMyService(error, info.componentStack);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return this.props.fallback;
    }

    return this.props.children;
  }
}
<ErrorBoundary fallback={<p>Something went wrong</p>}>
  <Profile />
</ErrorBoundary>

였λ₯˜ κ²½κ³„μ˜ μž₯점

  • 문제 λ°œμƒ μ‹œ 더 λ‚˜μ€ μ‚¬μš©μž κ²½ν—˜ 제곡

  • μ΅œμƒμœ„ 경둜 ꡬ성 μš”μ†Œμ—μ„œ λž˜ν•‘ν•˜μ—¬ κ°„νŽΈν•˜κ²Œ μ—λŸ¬ 관리 λ˜λŠ”

  • κ°œλ³„ μœ„μ ―λ§ˆλ‹€ λž˜ν•‘ν•˜μ—¬ ν•˜λ‚˜μ˜ μœ„μ ―μ—μ„œ μ—λŸ¬κ°€ λ°œμƒν•΄λ„ λ‹€λ₯Έ μœ„μ ―μ€ λŒ€ν™”ν˜•μœΌλ‘œ μœ μ§€ κ°€λŠ₯

κ΅¬ν˜„ 라이브러리

ν˜„μž¬λŠ” ν΄λž˜μŠ€ν˜• ꡬ성 μš”μ†Œλ₯Ό ν†΅ν•΄μ„œλ§Œ κ΅¬ν˜„μ΄ κ°€λŠ₯

https://github.com/bvaughn/react-error-boundary

Last updated