score:0

the closest concept of uncoughtexception in react is called "error boundaries":
https://reactjs.org/docs/error-boundaries.html

these elements will catch any rendering error which happen within their subtree.
within the render method you can display some kind of "internal error" message.

score:0

react 16 introduced error boundaries via a class component lifecycle method: componentdidcatch, however there are some caveats that you should read about in the documentation below.

componentdidcatch

/*
* implementation
*/
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;
  }
}


/*
* usage
*/
<errorboundary>
  <mywidget />
</errorboundary>

react-error-boundary

however, instead of implementing the above, i'd highly suggest using something like react-error-boundary from brian vaughn.

it's flexible, allows for error recovery, and doesn't outwardly rely on any react lifecycle methods.

import {errorboundary} from 'react-error-boundary'

const errorfallback = () => <div>something went wrong</div>

const myerrorhandler = (error: error, info: {componentstack: string}) => {
  // do something with the error
  // e.g. log to an error logging client here
}

const ui = (
  <errorboundary fallbackcomponent={errorfallback} onerror={myerrorhandler}>
    <componentthatmayerror />
  </errorboundary>,
)

Related Query

More Query from same tag