Event Handler Error Handling

Errors thrown inside event handlers are not caught by React error boundaries. Handle them explicitly in the handler, typically with `try/catch`, validation, and appropriate UI error state.

React error boundaries catch errors during rendering and certain React lifecycle work, but they do not catch errors thrown from event handlers. A click handler, form submission callback, or similar event callback therefore needs its own error-handling strategy.

For synchronous event-handler code, wrap the operation that may fail in `try/catch`. This lets the component convert an exception into useful behavior, such as setting an error message, logging the failure, or showing a fallback UI for that interaction.

For asynchronous work, handle rejected promises explicitly. A `try/catch` around an `await` inside an `async` handler can catch the rejection; alternatively, use a promise `.catch()` handler. An error boundary should not be treated as a general-purpose replacement for these local handlers.

Keep the `try` block focused on operations that can actually fail. This makes it easier to distinguish expected operational failures, such as a failed request, from programming bugs that should be surfaced during development and monitoring.

Key points

Interview questions

Are errors thrown inside React event handlers caught by error boundaries?

No. React error boundaries do not catch errors thrown from event handlers such as `onClick` or `onSubmit`. The handler should explicitly catch failures and decide how to report or recover from them. For example, it can use `try/catch` and update component state with an error message.

How would you handle a failure from an API call triggered by a button click?

Make the handler asynchronous and wrap the awaited request in `try/catch`. On success, update the relevant state; on failure, set an appropriate error state and optionally log the error. The UI can then display feedback such as a retry message.

Why shouldn't you rely on an error boundary as the error-handling mechanism for a form submission?

A form submission is an event-driven operation, and errors from its handler are outside the situations error boundaries are designed to catch. The handler needs to distinguish expected operational failures, such as validation or a server rejection, from unexpected exceptions. Local handling also lets the component provide specific feedback and recovery actions.

What is the correct pattern for errors in an async event handler?

Use an `async` handler and place the awaited operation inside a `try/catch`, or attach a rejection handler with `.catch()`. Make sure the promise is actually awaited or returned so the failure is observed. Then update UI state or perform another deliberate error-handling action.