react promise catch error code example

Example 1: promise catch

//create a Promise
var p1 = new Promise(function(resolve, reject) {
  resolve("Success");
});

//Execute the body of the promise which call resolve
//So it execute then, inside then there's a throw
//that get capture by catch
p1.then(function(value) {
  console.log(value); // "Success!"
  throw "oh, no!";
}).catch(function(e) {
  console.log(e); // "oh, no!"
});

Example 2: react catch error in component

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {    // Display fallback UI    this.setState({ hasError: true });    // You can also log the error to an error reporting service    logErrorToMyService(error, info);  }
  render() {
    if (this.state.hasError) {      // You can render any custom fallback UI      return <h1>Something went wrong.</h1>;    }    return this.props.children;
  }
}