错误处理并记录React js中的错误

时间:2018-03-22 11:44:39

标签: reactjs error-handling error-logging

我正在尝试处理错误并记录react js中的错误

我使用errorBoundary方法来处理错误,但它只支持react js version 16

clntSock = servSock.ClntSock.EndAccept(asyncResult)

我已经尝试了另一种反应版本15的方法,它工作正常。成功处理错误但无法记录错误

import React, {Component} from "react";
import "./App.css";
import errorimg from './errorimg.svg';

//create a erro boundry
class ErrorLimit extends Component {
  constructor(props) {
    super(props);
    this.state = { error: null, errorInfo: null };
  }

  //set the error value when invoked
  componentDidCatch(error, errorInfo) {
    this.setState({
      error: error,
      errorInfo: errorInfo
    })
    logErrorToMyService(error, info);
  }

  render() {
    //checked the error
    if (!!this.state.errorInfo) {
      return (
        <div className="snap">
          <img src= {errorimg}/>
          <div className="snap-message">
          {this.state.error && this.state.error.toString()}
          {this.state.errorInfo.componentStack} 
            <p> <b>Error occured - something's gone wrong.</b></p>
            <p>Anyway we handled error
            </p>
          </div>
        </div>
      );
    } else {

      return this.props.children;
    }
  }
}


class Widget extends Component {
  constructor(props) {
    super(props);
    this.state = { loading: true, n: 0 };
    this.getCount = this.getCount.bind(this)
  }

  
  getCount() {
    if (this.state.n > 3) throw new Error('woops..counter betes limit');
    return `(${this.state.n})`;
  }

  handleClick() {
    this.setState({ n: this.state.n + 1 });
  }
  
  render() {
    return (
      <div>
        <div>Counter widget {this.getCount(this.state.n)}</div>
        <button onClick={this.handleClick.bind(this)}>
          Click me a few times
        </button>
      </div>
    );
  }
}

class SampleApp extends Component {
  render() {
    return (
      <div className="sidebar">
      {/* here we used error boundry */}
        <ErrorLimit>
          <Widget />
        </ErrorLimit>
      </div>
    );
  }
}

class App extends Component {
  render() {
    return (
      <div className="app">
        <SampleApp />
      </div>
    );
  }
}

export default App;

任何人都建议一种方法来处理错误并在反应版本15中记录错误

1 个答案:

答案 0 :(得分:2)

React版本16.0及更高版本支持可以处理错误的错误边界。

在React 16.0之下,您需要按以下状态处理错误:

// Create a state variable for error. The initial state is false because there are no errors.
this.state = { hasError: false };

// Set hasError as true when an error is detected.
this.setState({ hasError: true });

if (this.state.hasError){
 // Do something, e.g. handle error.
}