Catch error

3 snippets across 2 stacks — JavaScript, React

Also written as catch all errors

JSJavaScript

try / catch / finally

JS · Error Handling
syntax
try { ... }
catch (error) { ... }
finally { ... }
example
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
process.on('unhandledRejection', handler)
window.addEventListener('unhandledrejection', handler)
example
// Browser global handler
window.addEventListener("unhandledrejection", (event) => {
  console.error("Unhandled rejection:", event.reason);
  event.preventDefault(); // prevents console error
  reportToService(event.reason);
});

// Node.js global handler
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.

REReact

Error Boundaries

RE · Patterns
syntax
// Error boundaries must be class components (as of React 19)
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
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;
  }
}

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