React에서 error 다루기

박상욱·2022년 3월 5일
0

React

목록 보기
13/20

ErrorBoundary


ErrorBoundary?

React에서 erorr를 다루는 방법은 여러가지가 있을 것이다. 그 중에서
ErrorBoundary 이용해서 error를 처리 해볼 것이다.

만약 react에서 error가 생기면 js전체가 그 기능을 못하고 화면에 아무것도 표출하지 못한다.
child에서 error가나면 적어도 child가 아닌 component는 그려져야 하는게 아닌가 라고 생각할 수 있지만
그렇지 않다.

이방법을 해결하기 위해서 사용하는것이 React 16에 도입된 에러 경계(“error boundary”)이다.

에러 경계는 하위 컴포넌트 트리의 어디에서든 자바스크립트 에러를 기록하며 깨진 컴포넌트
트리 대신 폴백 UI를 보여주는 React 컴포넌트이다.


✔️특이점

함수형 x class component로 만들어야함.


✔️코드

    <script type="text/babel">
      const rootElement = document.getElementById("root");

      class ErrorBoundary extends React.Component {
        state = { error: null };
        static getDerivedStateFromError(error) {
          return { error };
        }

        render() {
          const { error } = this.state;
          if (error) {
            return <this.props.fallback error={error} />;
            // return this.props.fallback;
            // return <p> there is some error...</p>;
          }
          return this.props.children;
        }
      }

      const Child = () => {
        throw new Error("somthing Wrong...");
        return <p>child....</p>;
      };

      const Fallback = ({ error }) => {
        alert(error.message);
        return <p>there is some error</p>;
      };
      const App = () => {
        return (
          <>
            <p>APP</p>
            <ErrorBoundary fallback={Fallback}>
              <Child />
            </ErrorBoundary>
          </>
        );
      };

      ReactDOM.render(<App />, rootElement);
    </script>

✔️코드 살펴보기

<ErrorBoundary></ErrorBoundary>

<ErrorBoundary fallback={Fallback}>
    <Child />
</ErrorBoundary>

class형 component로 ErrorBoundary component를 만들고 error가 날경우 대체할 component에 감싸준다.
child를 감싸놓고 child안에서 error가나면 특정한 화면을 보여준다.

getDerivedStateFromError

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

error가 났을때 state를 어디에 set할 것인가하는 구문이고 다음 렌더링에서 폴백 UI가 보이도록 상태를 업데이트한다.

Fallback

const Fallback = ({ error }) => {
  alert(error.message);
  return <p>there is some error</p>;
};
<ErrorBoundary fallback={Fallback}>
  <Child />
</ErrorBoundary>

fallback은 ERROR 발생시 보여줄 UI를 반환한다.
<ErrorBoundary fallback={<Fallback />}> 이렇게 jsx로 넘겨주면 안되고 함수로 넘겨줘야한다.


✔️결과

errorBoundary로 감싸지 않으면.

warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: . Did you accidentally export a JSX literal instead of a component?
at ErrorBoundary (:44:5)
at App

으로 추적할수있고

errorBoundary로 감싸면
Fallback으로 넘긴 Component가 반환된것을 볼 수 있다.


✔️주의

에러 경계는 다음과 같은 에러는 포착하지 않습니다.

  • 이벤트 핸들러 (더 알아보기)
  • 비동기적 코드 (예: setTimeout 혹은 requestAnimationFrame 콜백)
  • 서버 사이드 렌더링
  • 자식에서가 아닌 에러 경계 자체에서 발생하는 에러

✔️참고

error Boundary react 공식

profile
개발자

0개의 댓글