// Browser global handlerwindow.addEventListener("unhandledrejection",(event)=>{console.error("Unhandled rejection:", event.reason);
event.preventDefault();// prevents console errorreportToService(event.reason);});// Node.js global handlerprocess.on("unhandledRejection",(reason, promise)=>{console.error("Unhandled rejection at:", promise,"reason:", reason);});
Note Global handlers are your safety net -- they should log and report, not silently swallow errors. Always prefer local try/catch for known async operations.
// Error boundaries must be class components (as of React 19)classErrorBoundaryextendsReact.Component{
state ={ hasError:false};staticgetDerivedStateFromError(error){return{ hasError:true};}componentDidCatch(error, info){logError(error, info);}render(){if(this.state.hasError)return<Fallback/>;returnthis.props.children;}}
Example
classAppErrorBoundaryextendsReact.Component{constructor(props){super(props);this.state={ hasError:false, error:null};}staticgetDerivedStateFromError(error){return{ hasError:true, error };}componentDidCatch(error, errorInfo){reportToService(error, errorInfo.componentStack);}render(){if(this.state.hasError){return(<div className="error-screen"><h1>Something went wrong</h1><button onClick={()=>this.setState({ hasError:false})}>Try again
</button></div>);}returnthis.props.children;}}// Wrap sections of the UI<AppErrorBoundary><Dashboard/></AppErrorBoundary>
Note Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the tree below them. They do NOT catch errors in event handlers, async code, or server-side rendering. Use try/catch for those.
Frequently asked questions
How do you catch error?
This task is covered in 2 stacks on this page: JavaScript, React. The "try / catch / finally" snippet in JavaScript uses `try { ... }`.
Which code does the JavaScript example use?
The "try / catch / finally" snippet uses `try { ... }`, from the Error Handling section of the JavaScript cheat sheet.
Which stacks cover "catch error" on this page?
JavaScript, React. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "try / catch / finally": finally always runs, whether the try succeeded or catch was triggered. It even runs if try or catch contains a return statement.