Search code examples
reactjserror-handlingerror-logging

Error Handle and Log the errors in React js


I'm trying to handle the error and logging the errors in react js

I used errorBoundary method to handle the error but it's only support for the react js version 16

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;

and I have tried another method for react version 15, It's work fine. Successfully handle the error but can't log the error

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import wrapWithTryCatch from 'react-try-catch-render';
import errorimg from './errorimg.svg';
 
class MyErrorHandler extends React.Component {
    render(){
        return (
            <div className="App-header">{this.props.error}</div>
        );
    }
}
 
class App extends React.Component {
 
  constructor(props) {
    super(props);
    this.state = { loading: true, n: 0 };
    this.getCount = this.getCount.bind(this)
    this.handleClick = this.handleClick.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>
    );
  }
}
 
 
export default wrapWithTryCatch(React, MyErrorHandler, {error: "Error catched!"})(App);

Anyone please suggest a method to handle the error and log the error in react version 15


Solution

  • React versions 16.0 and above support error boundaries which can handle the errors.

    Below React 16.0, you need to handle errors by state like:

    // 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.
    }