All stacks / Intents / Catch error Also written as catch all errors
try / catch / finally JS · Error Handling syntax Copy
try { ... }
catch (error) { ... }
finally { ... }example Copy
function parseConfig(jsonString) {
try {
return JSON.parse(jsonString);
} catch (error) {
console.error("Invalid config JSON:" , error.message);
return {};
} finally {
console.log("Config parsing attempted." );
}
}
const config = parseConfig('{"debug": true}' );
console.log(config);output
"Config parsing attempted."
{ debug: true }Note finally always runs, whether the try succeeded or catch was triggered. It even runs if try or catch contains a return statement.
Centralized Async Error Handling JS · Error Handling syntax Copy
process.on('unhandledRejection' , handler)
window.addEventListener('unhandledrejection' , handler)example Copy
window.addEventListener("unhandledrejection" , (event) => {
console.error("Unhandled rejection:" , event.reason);
event.preventDefault();
reportToService(event.reason);
});
process.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 RE · Patterns syntax Copy
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) { logError(error, info); }
render() {
if (this .state.hasError) return <Fallback />;
return this .props.children;
}
}example Copy
class AppErrorBoundary extends React.Component {
constructor(props) {
super (props);
this .state = { hasError: false , error: null };
}
static getDerivedStateFromError(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>
);
}
return this .props.children;
}
}
<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.
Related tasks