React Native Expo Native Modules addListener native crashes

I was recently writing Expo Native Module on iOS and Android for a client and came across a very puzzling crash that took awhile to figure out.

Whenever some new code was executing around the native module the app was crashing natively with no clear reason why. We have tons of error boundary etc handling in our app already so JS errors do not cause a native crash so things were getting very strange.

I’ll avoid the gory details here and cut to the chase: you can easily have a native crash with Expo native modules if you use the emitter.addListener API and have an error in JAVASCRIPT CODE even if you are using error boundaries etc.

The below throw new Error("Native Crash!") will cause your application to have a native crash even though you are in JS. Note the other throw new Error("Not a Native Crash!") will not cause a native crash.

import { requireNativeModule, NativeModule } from 'expo';

type ClipboardChangeEvent = {
  contentTypes: string[];
};

type ClipboardModuleEvents = {
  onClipboardChanged(event: ClipboardChangeEvent): void;
};

declare class ClipboardModule extends NativeModule<ClipboardModuleEvents> {}

const Clipboard = requireNativeModule<ClipboardModule>('Clipboard');

Clipboard.addListener('onClipboardChanged', (event: ClipboardChangeEvent) => {
  throw new Error("Native Crash!")});

throw new Error("Not a Native Crash!")

I’m not sure why this is the case, I’m guessing its likely due to the JS stack being executed from a native stack and any exceptions get back to native… but something to be aware of and avoid. Add exception handling in these cases inside an addListener event.

Leave a Reply

Your email address will not be published. Required fields are marked *

Proudly powered by WordPress | Theme: Cute Blog by Crimson Themes.