오류 경계가 있는 강력한 프런트엔드 예외 관리오류 경계가 있는 강력한 프런트엔드 예외 관리

오류 경계가 있는 강력한 프런트엔드 예외 관리

런타임 실패 시 대체 렌더링 상태를 구현하고 충돌 세부 정보를 웹후크 로깅에 깔끔하게 스트리밍합니다.

오류 경계가 중요한 이유

React 애플리케이션에서는 구성 요소에서 발견되지 않은 단일 JavaScript 오류로 인해 전체 UI가 중단될 수 있습니다. Error Boundaries 이전에는 이는 사용자에게 무엇이 잘못되었는지 표시하지 않고 흰색 화면을 표시한다는 것을 의미했습니다. 오류 경계는 하위 구성 요소 트리의 어느 위치에서나 JavaScript 오류를 포착하고 충돌 대신 대체 UI를 렌더링하는 React 구성 요소입니다.

오류 경계 구현

오류 경계는 정적 수명 주기 메서드 getDerivedStateFromError 및 comComponentDidCatch 중 하나 또는 둘 다를 구현하는 클래스 구성 요소입니다.

import React, { Component, ErrorInfo, ReactNode } from "react";

interface Props {
  children: ReactNode;
  fallback?: ReactNode;
}

interface State {
  hasError: boolean;
  error: Error | null;
}

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

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

  componentDidCatch(error: Error, info: ErrorInfo) {
    console.error("Error caught:", error, info.componentStack);
    // Send to logging service
    logErrorToService(error, info);
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback || <DefaultFallback error={this.state.error} />;
    }
    return this.props.children;
  }
}

대체 UI 디자인

좋은 대체 UI는 복구 옵션을 제공하고 사용자 불만을 줄여줍니다.

function DefaultFallback({ error }: { error: Error | null }) {
  return (
    <div role="alert" className="error-boundary-fallback">
      <h2>Something went wrong</h2>
      <p>We encountered an unexpected error. Please try refreshing the page.</p>
      <button onClick={() => window.location.reload()}>
        Refresh Page
      </button>
      {process.env.NODE_ENV === "development" && (
        <pre>{error?.message}</pre>
      )}
    </div>
  );
}

로깅 서비스(Sentry)와 통합

Error Boundaries는 Sentry와 같은 오류 모니터링 도구와 자연스럽게 통합됩니다.

import * as Sentry from "@sentry/react";

class SentryErrorBoundary extends Component<Props, State> {
  componentDidCatch(error: Error, info: ErrorInfo) {
    Sentry.withScope((scope) => {
      scope.setExtras({ componentStack: info.componentStack });
      Sentry.captureException(error);
    });
  }
}

Sentry는 내장된 Error Boundary 래퍼도 제공합니다.

<Sentry.ErrorBoundary fallback={<ErrorFallback />}>
  <App />
</Sentry.ErrorBoundary>

경계 배치 전략

오류 경계를 전략적으로 배치하는 것이 중요합니다.

App
├── ErrorBoundary (global fallback)
│   ├── Layout
│   │   ├── Header
│   │   ├── ErrorBoundary (content area fallback)
│   │   │   ├── MainContent
│   │   │   └── DataTable
│   │   └── Footer
│   └── ErrorBoundary (sidebar fallback)
│       └── SidebarWidget

가이드라인:

  • 각 주요 섹션(사이드바, 메인 콘텐츠, 모달)을 독립적으로 래핑합니다.
  • 최후의 수단으로만 루트 경계를 사용하십시오.
  • 실패를 복구할 수 있는 기능 경계에 경계를 배치합니다.
  • UI의 정상적인 부분이 계속 작동하도록 허용

오류 복구 패턴

대체를 표시하는 것 외에도 Error Boundaries는 복구 기능을 제공할 수 있습니다.

class RecoverableBoundary extends Component {
  state = { hasError: false, error: null };

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

  handleRetry = () => {
    this.setState({ hasError: false, error: null });
  };

  render() {
    if (this.state.hasError) {
      return (
        <div>
          <p>Error: {this.state.error?.message}</p>
          <button onClick={this.handleRetry}>Retry</button>
        </div>
      );
    }
    return this.props.children;
  }
}

제한사항

오류 경계에는 이해해야 할 중요한 제한 사항이 있습니다.

제한사항설명
이벤트 핸들러‘onClick’ 등의 오류는 포착되지 않습니다. try-catch
비동기 코드setTimeout 또는 Promise 오류가 발생하지 않습니다
SSR오류 경계는 서버 측 오류를 포착하지 않습니다
자신의 오류오류 경계는 자체 오류를 포착할 수 없습니다
상태 돌연변이손상된 전역 상태를 처리하도록 설계되지 않음

결론

오류 경계는 프로덕션 React 애플리케이션의 필수 부분입니다. 전체 UI 충돌을 방지하고, 적절한 성능 저하를 제공하며, 로깅 서비스와 원활하게 통합됩니다. 전략적 경계 배치와 적절한 오류 로깅 및 복구 패턴을 결합하면 오류를 적절하게 처리하고 개발자에게 실행 가능한 진단을 제공하는 애플리케이션을 구축할 수 있습니다.