IT/React

React - 에러처리

최고영회 2019. 3. 27. 20:27
728x90
반응형
SMALL

최근 버전의 리액트는 오류 경계(error boundaries)라는 개념을 도입했다. 

만일 컴포넌트의 생성자, render 메서드 혹은 생명주기 메서드 내에서 처리되지 않은 예외가 발생하면 리액트는 컴포넌트와 그 자식 컴포넌트들을 DOM으로 부터 언마운트 한다. 

이 방법은 에러를 해당 컴포넌트 내에 격리함으로써 앱의 나머지 부분들이 계속 원활히 동작하도록 할 수 있다는 장점이 있다.

React.Component 클래스로부터 파생된 컴포넌트의 경우 componentDidCatch 메서드로 처리할 수 있다.

이 메서드는 try-catch 구문의 동작과 유사하다. 

예제 소스를 통해 살펴 보자. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import React from "react";
import { render } from "react-dom";
import PropTypes from "prop-types";
 
class ChildComponent extends React.Component {
  static propTypes = {
    name: PropTypes.string
  };
  static defaultProps = (function() {
    console.log("ChildComponent : defaultProps");
    return {};
  })();
  constructor(props) {
    super(props);
    console.log("ChildComponent: state");
    this.state = {
      name"Mark"
    };
    this.oops = this.oops.bind(this);
  }
  oops() {
    this.setState(() => ({ oops: true }));
  }
  render() {
    if (this.state.oops) {
      throw new Error("Something went wrong");
    }
    console.log("ChildComponent: render");
    return [
      <div key="name">Name: {this.props.name}</div>,
      <button key="error" onClick={this.oops}>
        Create error
      </button>
    ];
  }
}
 
class ParentComponent extends React.Component {
  static defaultProps = (function() {
    console.log("ParentComponent: defaultProps");
    return {
      truefalse
    };
  })();
  constructor(props) {
    super(props);
    console.log("ParentComponent: state");
    this.state = { text"" };
    this.onInputChange = this.onInputChange.bind(this);
  }
  onInputChange(e) {
    const text = e.target.value;
    this.setState(() => ({ texttext }));
  }
  componentDidCatch(err, errorInfo) {
    console.log("componentDidCatch");
    console.error(err);
    console.error(errorInfo);
    this.setState(() => ({ err, errorInfo }));
  }
  render() {
    console.log("ParentComponent: render");
    if (this.state.err) {
      return (
        <details style={{ whiteSpace: "pre-wrap" }}>
          {this.state.error && this.state.error.toString()}
          <br />
          {this.state.errorInfo.componentStack}
        </details>
      );
    }
    return [
      <h2 key="h2">Learn about rendering and lifecycle methods!</h2>,
      <input
        key="input"
        value={this.state.text}
        onChange={this.onInputChange}
      />,
      <ChildComponent key="ChildComponent" name={this.state.text/>
    ];
  }
}
 
render(<ParentComponent />, document.getElementById("root"));
 




버튼을 클릭해 보면 아래와 같이 에러 상세 메시지를 볼 수 있다. 


728x90
반응형
LIST