ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Error 처리
    Programming/JavaScript & TypeScript 2022. 5. 3. 21:29
    728x90

    JS와 React를 개발하다보면 UI에서 Error가 난 경우에는 아무것도 보여지지 않는다. 

    Error가 발생하기 전까지는 그려져야할것 같은데, JS나 React에서는 그렇지 않다. (왜인지는 모르겠다.)

     

    이번에 다룰 내용은 UI에서 Error가 났을 때, 해당 컴포넌트만 Error를 처리하는 방법이다.

    여기서 참고했다.. 

    https://ko.reactjs.org/docs/concurrent-mode-suspense.html#handling-errors

    기본 코드 

    App과 Child Component가 있고, Child에서 Error를 발생시켜보자 

    더보기
    <!DOCTYPE html>
    <html>
      <body>
        <div id="root"></div>
        <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
        <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
        <script src="https://unpkg.com/@babel/standalone@7.17.11/babel.min.js"></script>
    
        <script type="text/babel">
          const rootElement = document.getElementById("root");
    
          const Child = () => {
            return <p> Child... </p>;
          };
    
          const App = () => {
            return (
              <>
                <p> App </p>
                <Child />
              </>
            );
          };
          ReactDOM.render(<App />, rootElement);
        </script>
      </body>
    </html>

     

    기본 Error 발생 시키기

    console에 Error가 나오며, 브라우저에는 아무것도 나오지 않는다. 

    더보기

    Child안에서 'throw new Error()' 를 적어보자 

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

     

    그렇다면, Error가 나도 App은 그려지는 것을 원한다. 

     

    ErrorBoundary를 이용하자 

    ErrorBoundary를 이용하여 자식을 감싸고, 자식안에서 Error가 발생하면 ErrorBoundary의 화면을 보여주도록 하자 

    더보기

    ErrorBoundary를 Class Component로 만들자 

    이제는 Error가 나도 App Compoenent는 보여진다.

    <!DOCTYPE html>
    <html>
      <body>
        <div id="root"></div>
        <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
        <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
        <script src="https://unpkg.com/@babel/standalone@7.17.11/babel.min.js"></script>
    
        <script type="text/babel">
          const rootElement = document.getElementById("root");
    
    	  // ErrorBoundary 생성
          class ErrorBoundary extends React.Component {
            state = { error: null };
            static getDerivedStateFromError(error) {
              return { error };
            }
    
            render() {
              const { error } = this.state;
              //Error가 있으면 P tag의 내용을 보여주고 
              if (error) {
                return <p> there is some error </p>;
              }
              //없으면 원래 자식을 보여주자 
              return this.props.children;
            }
          }
    
          const Child = () => {
            throw new Error();
            return <p> Child... </p>;
          };
    
          const App = () => {
            return (
              <>
                <p> App </p>
                
                <ErrorBoundary>
                  <Child />
                </ErrorBoundary>
              </>
            );
          };
          ReactDOM.render(<App />, rootElement);
        </script>
      </body>
    </html>

     

    조금더 코드를 다듬어 보면..

    fallback을 이용해도 된다. 

    <ErrorBoundary fallback={<p> there is SomeError...</p>}>

    더보기
    fallback 이용
    <!DOCTYPE html>
    <html>
      <body>
        <div id="root"></div>
        <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
        <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
        <script src="https://unpkg.com/@babel/standalone@7.17.11/babel.min.js"></script>
    
        <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;
              }
              return this.props.children;
            }
          }
    
          const Child = () => {
            throw new Error();
            return <p> Child... </p>;
          };
    
          const App = () => {
            return (
              <>
                <p> App </p>
                <ErrorBoundary fallback={<p> there is SomeError...</p>}>
                  <Child />
                </ErrorBoundary>
              </>
            );
          };
          ReactDOM.render(<App />, rootElement);
        </script>
      </body>
    </html>

    Fallback을 따로 뽑아서도 사용가능하다

    alert를 넣을 수도 있다.

    더보기
    <!DOCTYPE html>
    <html>
      <body>
        <div id="root"></div>
        <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
        <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
        <script src="https://unpkg.com/@babel/standalone@7.17.11/babel.min.js"></script>
    
        <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.children;
            }
          }
    
          const Child = () => {
            throw new Error();
            return <p> Child... </p>;
          };
    
          const Fallback = ({ error }) => {
            alert(error);
            return <p> THERE is SOME ERROR...</p>;
          };
    
          const App = () => {
            return (
              <>
                <p> App </p>
                <ErrorBoundary fallback={Fallback}>
                  <Child />
                </ErrorBoundary>
              </>
            );
          };
          ReactDOM.render(<App />, rootElement);
        </script>
      </body>
    </html>

    'Programming > JavaScript & TypeScript' 카테고리의 다른 글

    [React 라이브러리] 스타일링 라이브러리  (0) 2022.05.10
    [React 라이브러리] 라이브러리 기초  (0) 2022.05.09
    Redux Toolkit  (0) 2022.04.01
    typescript class  (0) 2022.02.20
    typescript Interface  (0) 2022.02.18
Designed by Tistory.