Skip to content

fix: don't call onMessage callback twice when it throws - #503

Open
RaphaelFakhri wants to merge 1 commit into
callstack:mainfrom
RaphaelFakhri:fix/onmessage-callback-error
Open

RaphaelFakhri wants to merge 1 commit into
callstack:mainfrom
RaphaelFakhri:fix/onmessage-callback-error

Conversation

@RaphaelFakhri

Copy link
Copy Markdown

Summary

ReactNativeBrownfield.onMessage wraps both JSON.parse and the user callback in one try/catch. When the callback throws while it handles a valid JSON message, the catch branch calls the callback a second time, now with the raw message string as data. The original error is lost.

For example, with a native host that posts {"type":"login"}:

ReactNativeBrownfield.onMessage((event) => {
  handle((event.data as { type: string }).type); // throws inside handle()
});

The callback runs once with { type: 'login' }, then again with '{"type":"login"}'. The second call reads .type of a string and the original error from handle() never reaches the developer.

This change limits the try/catch to JSON.parse and calls the callback once, outside of it. Errors thrown by the callback now propagate as they do for any other event listener.

Test plan

  • Added packages/react-native-brownfield/src/__tests__/onMessage.test.ts, which covers JSON payloads, non-JSON payloads, a throwing callback and remove().
  • Without the fix, does not call the callback again when it throws fails because the callback is called twice. With the fix, all 4 tests pass.
  • yarn test, yarn lint and yarn typecheck in packages/react-native-brownfield pass (13 files, 114 tests).
  • Added a patch changeset for @callstack/react-native-brownfield.

Copilot AI balanced review requested due to automatic review settings October 19, 2026 06:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants