### iOS Setup with CocoaPods Source: https://geh.darshan09200.dev/docs/overview/installation Runs CocoaPods to install native dependencies for iOS after the package has been installed. This is a standard step for React Native iOS projects. ```bash cd ios && pod install ``` -------------------------------- ### Install react-native-restart for App Restart Source: https://geh.darshan09200.dev/docs/examples/advanced-examples Installs the react-native-restart package using various package managers (npm, Yarn, pnpm, Bun). This package is a dependency for restarting the application after a fatal error. ```bash npm install react-native-restart ``` ```bash yarn add react-native-restart ``` ```bash pnpm add react-native-restart ``` ```bash bun add react-native-restart ``` -------------------------------- ### Install react-native-global-exception-handler with Bun Source: https://geh.darshan09200.dev/docs/overview/getting-started Installs the react-native-global-exception-handler package using Bun and links native dependencies by running `pod install` for iOS. This is the standard installation method for Bun users. ```bash bun add react-native-global-exception-handler cd ios && pod install ``` -------------------------------- ### Install react-native-global-exception-handler with npm Source: https://geh.darshan09200.dev/docs/overview/getting-started Installs the react-native-global-exception-handler package using npm and links native dependencies by running `pod install` for iOS. This is the standard installation method for npm users. ```bash npm install react-native-global-exception-handler cd ios && pod install ``` -------------------------------- ### Install react-native-global-exception-handler with pnpm Source: https://geh.darshan09200.dev/docs/overview/getting-started Installs the react-native-global-exception-handler package using pnpm and links native dependencies by running `pod install` for iOS. This is the standard installation method for pnpm users. ```bash pnpm add react-native-global-exception-handler cd ios && pod install ``` -------------------------------- ### Install react-native-global-exception-handler with Yarn Source: https://geh.darshan09200.dev/docs/overview/getting-started Installs the react-native-global-exception-handler package using Yarn and links native dependencies by running `pod install` for iOS. This is the standard installation method for Yarn users. ```bash yarn add react-native-global-exception-handler cd ios && pod install ``` -------------------------------- ### Install Package with Bun Source: https://geh.darshan09200.dev/docs/overview/installation Installs the react-native-global-exception-handler package using Bun. Bun is a fast JavaScript runtime, bundler, transpiler, and package manager. ```bash bun add react-native-global-exception-handler ``` -------------------------------- ### Install Package with Yarn Source: https://geh.darshan09200.dev/docs/overview/installation Installs the react-native-global-exception-handler package using Yarn. Yarn is an alternative package manager for Node.js. ```bash yarn add react-native-global-exception-handler ``` -------------------------------- ### Update Dependencies: Bun Source: https://geh.darshan09200.dev/docs/migration/migrating-from-react-native-exception-handler Commands to uninstall the old package and install the new one using Bun, followed by installing pods for iOS. ```bash bun remove react-native-exception-handler bun add react-native-global-exception-handler cd ios && pod install ``` -------------------------------- ### Install Package with npm Source: https://geh.darshan09200.dev/docs/overview/installation Installs the react-native-global-exception-handler package using npm. This is the standard package manager for Node.js projects. ```bash npm install react-native-global-exception-handler ``` -------------------------------- ### Install Older Exception Handler Package Source: https://geh.darshan09200.dev/docs/troubleshooting Offers commands to install the `react-native-exception-handler` package using various package managers (npm, Yarn, pnpm, Bun) for users who need to maintain compatibility with older React Native versions. ```bash npm install react-native-exception-handler ``` ```bash yarn add react-native-exception-handler ``` ```bash pnpm add react-native-exception-handler ``` ```bash bun add react-native-exception-handler ``` -------------------------------- ### Clean and Reinstall iOS Pods Source: https://geh.darshan09200.dev/docs/troubleshooting Steps to clean the existing Pods directory and Podfile.lock, then deintegrate and reinstall pods to fix iOS installation issues. ```bash cd ios rm -rf Pods Podfile.lock pod deintegrate pod install cd .. ``` -------------------------------- ### Quick Setup for Global Exception Handling in React Native Source: https://geh.darshan09200.dev/docs/overview/getting-started Demonstrates how to set up JavaScript and native exception handling in a React Native application using `react-native-global-exception-handler`. It configures handlers to log errors and optionally send them to a monitoring service, with options for graceful recovery. ```javascript import { setJSExceptionHandler, setNativeExceptionHandler } from 'react-native-global-exception-handler'; // Handle JavaScript exceptions setJSExceptionHandler((error, isFatal) => { console.log('JS Exception:', error, isFatal); // Send to error monitoring service }, true); // Enable in dev mode // Handle native exceptions setNativeExceptionHandler((errorString) => { console.log('Native Exception:', errorString); // Send to error monitoring service }, { forceAppToQuit: true, callPreviouslyDefinedHandler: false }); ``` -------------------------------- ### Configure Kotlin Version for Android Build Source: https://geh.darshan09200.dev/docs/troubleshooting Example of setting the Kotlin version in the android/build.gradle file, which can resolve Android build failures. ```gradle buildscript { ext { kotlinVersion = "1.8.0" } } ``` -------------------------------- ### Install Package with pnpm Source: https://geh.darshan09200.dev/docs/overview/installation Installs the react-native-global-exception-handler package using pnpm. pnpm is a performant package manager for Node.js. ```bash pnpm add react-native-global-exception-handler ``` -------------------------------- ### Update Dependencies: pnpm Source: https://geh.darshan09200.dev/docs/migration/migrating-from-react-native-exception-handler Commands to uninstall the old package and install the new one using pnpm, followed by installing pods for iOS. ```bash pnpm remove react-native-exception-handler pnpm add react-native-global-exception-handler cd ios && pod install ``` -------------------------------- ### Update Dependencies: npm Source: https://geh.darshan09200.dev/docs/migration/migrating-from-react-native-exception-handler Commands to uninstall the old package and install the new one using npm, followed by installing pods for iOS. ```bash npm uninstall react-native-exception-handler npm install react-native-global-exception-handler cd ios && pod install ``` -------------------------------- ### Complete Exception Handling Setup in React Native Source: https://geh.darshan09200.dev/docs/usage/usage Combines both JavaScript and Native exception handling setup in the application's entry point. This ensures that all types of errors are caught and can be logged or managed appropriately, providing a robust error handling strategy. ```javascript import { setJSExceptionHandler, setNativeExceptionHandler } from 'react-native-global-exception-handler'; // JavaScript exception handler setJSExceptionHandler((error, isFatal) => { // Send to monitoring service console.log('JS Error:', error, isFatal); }, true); // Native exception handler setNativeExceptionHandler((errorString) => { // Send to monitoring service console.log('Native Error:', errorString); }, { forceAppToQuit: true, callPreviouslyDefinedHandler: false }); ``` -------------------------------- ### iOS Native Crash Handling Example (JavaScript) Source: https://geh.darshan09200.dev/docs/usage/native-crash-handling An example demonstrating how to set up the native exception handler specifically for iOS. It logs the error and suggests reporting it to analytics. Remember to call `releaseExceptionHold()` on iOS for graceful crashing. ```javascript import { setNativeExceptionHandler } from 'react-native-global-exception-handler'; setNativeExceptionHandler((errorString) => { // Log the error console.log('iOS Native Crash:', errorString); // Report to analytics }); ``` -------------------------------- ### Update CocoaPods for iOS Installation Source: https://geh.darshan09200.dev/docs/troubleshooting Command to update CocoaPods to the latest version to resolve potential compatibility issues during iOS pod installation. ```bash sudo gem install cocoapods ``` -------------------------------- ### Update Dependencies: Yarn Source: https://geh.darshan09200.dev/docs/migration/migrating-from-react-native-exception-handler Commands to uninstall the old package and install the new one using Yarn, followed by installing pods for iOS. ```bash yarn remove react-native-exception-handler yarn add react-native-global-exception-handler cd ios && pod install ``` -------------------------------- ### Implement App Restart on Fatal JS Error Source: https://geh.darshan09200.dev/docs/examples/advanced-examples Sets up a JavaScript exception handler using react-native-global-exception-handler. If a fatal error occurs, it displays an alert to the user and provides an option to restart the app using react-native-restart. ```javascript import { Platform, Alert } from 'react-native'; import RNRestart from 'react-native-restart'; import { setJSExceptionHandler, setNativeExceptionHandler } from 'react-native-global-exception-handler'; setJSExceptionHandler((error, isFatal) => { if (isFatal) { Alert.alert( 'Unexpected error occurred', ` Error: ${isFatal ? 'Fatal' : ''} ${error.name} ${error.message} We will need to restart the app. `, [ { text: 'Restart', onPress: () => { RNRestart.Restart(); }, }, ] ); } }); setNativeExceptionHandler((errorString) => { //You can do something like call an api to report to dev team here ... ... // When you call setNativeExceptionHandler, react-native-global-exception-handler sets a // Native Exception Handler popup which supports restart on error in case of android. // In case of iOS, it is not possible to restart the app programmatically, so we just show an error popup and close the app. // To customize the popup screen take a look at CUSTOMIZATION section. }, { forceAppToQuit: true }); ``` -------------------------------- ### Verify Handler Execution with AsyncStorage Source: https://geh.darshan09200.dev/docs/advanced/testing This example shows how to verify that your native exception handler is being called by logging the error locally using AsyncStorage and then reporting it to an analytics service. It also includes a snippet to retrieve and log the last crash data. ```javascript import AsyncStorage from '@react-native-async-storage/async-storage'; setNativeExceptionHandler(async (errorString) => { // Log locally for verification await AsyncStorage.setItem('lastNativeCrash', JSON.stringify({ error: errorString, timestamp: new Date().toISOString() })); // Send to analytics reportToAnalytics(errorString); }); // Later, check if handler was called AsyncStorage.getItem('lastNativeCrash').then(data => { if (data) { console.log('Last crash:', JSON.parse(data)); } }); ``` -------------------------------- ### Replace Error Screen Activity (Android) Source: https://geh.darshan09200.dev/docs/examples/basic-examples Customizes the default error screen activity for Android by replacing it with a custom activity. This requires modifying the `MainApplication.kt` file and providing a `CustomErrorActivity` class. ```kotlin // In MainApplication.kt GlobalExceptionHandlerModule.replaceErrorScreenActivityClass(CustomErrorActivity::class.java) ``` -------------------------------- ### Chaining JS Handlers: JavaScript Source: https://geh.darshan09200.dev/docs/migration/migrating-from-react-native-exception-handler Example of how to chain existing JavaScript exception handlers using `getJSExceptionHandler` and `setJSExceptionHandler`. ```javascript const prev = getJSExceptionHandler(); setJSExceptionHandler((e, fatal) => { // custom logic if (prev) prev(e, fatal); }, true); ``` -------------------------------- ### Simulate Native Crash for Testing (JavaScript) Source: https://geh.darshan09200.dev/docs/examples/basic-examples Provides a function to simulate native crashes within a React Native application during development. This is useful for testing the native exception handler's behavior. ```javascript import { simulateNativeCrash } from 'react-native-global-exception-handler'; // Trigger an array bounds crash simulateNativeCrash('array_bounds'); ``` -------------------------------- ### Minimal Native Handler Configuration (JavaScript) Source: https://geh.darshan09200.dev/docs/examples/basic-examples Configures the native exception handler with essential options. It forces the application to quit and prevents calling any previously defined native handlers. ```javascript setNativeExceptionHandler(handlerFn, { forceAppToQuit: true, callPreviouslyDefinedHandler: false }); ``` -------------------------------- ### Avoid Memory Leaks in Exception Handlers Source: https://geh.darshan09200.dev/docs/troubleshooting Illustrates how closures can cause memory leaks by holding references to large data. It contrasts a bad example with a good example where data is fetched only when needed, preventing unnecessary memory retention. ```javascript // ❌ Bad - Closure captures large data let largeData = /* ... */; setJSExceptionHandler((error, isFatal) => { console.log(largeData); // Keeps largeData in memory }, true); // ✅ Good - No closure captures setJSExceptionHandler((error, isFatal) => { // Get fresh data when needed const data = getCurrentData(); console.log(data); }, true); ``` -------------------------------- ### Chain Previous JS Exception Handler (JavaScript) Source: https://geh.darshan09200.dev/docs/examples/basic-examples Demonstrates how to chain a new JavaScript exception handler with a previously defined one. This allows for adding custom logic while ensuring that the original handler also processes the exception. ```javascript import { setJSExceptionHandler, getJSExceptionHandler } from 'react-native-global-exception-handler'; const prev = getJSExceptionHandler(); setJSExceptionHandler((e, fatal) => { // custom logic if (prev) prev(e, fatal); }); ``` -------------------------------- ### TypeScript Type Imports Source: https://geh.darshan09200.dev/docs/overview/installation Imports necessary types for the react-native-global-exception-handler library when using TypeScript. These types help with static analysis and code completion. ```typescript import type { ExceptionHandlerOptions, JSExceptionHandler, NativeExceptionHandler, CrashType } from 'react-native-global-exception-handler'; ``` -------------------------------- ### Display Full Error Dialog for Fatal JS Errors (JavaScript) Source: https://geh.darshan09200.dev/docs/examples/basic-examples Sets up a JavaScript exception handler that displays a full alert dialog when a fatal error occurs. This dialog prompts the user to restart the app or report the error, allowing for custom restart and reporting logic. ```javascript import { setJSExceptionHandler } from 'react-native-global-exception-handler'; import { Alert } from 'react-native'; setJSExceptionHandler((error, fatal) => { if (!fatal) return; Alert.alert( 'App Error', `A fatal error occurred and the app needs to restart.\n${error.message}`, [ { text: 'Restart', onPress: () => {/* implement restart logic */} }, { text: 'Report', onPress: () => {/* send to analytics */} } ] ); }); ``` -------------------------------- ### Chain Native Exception Handlers Source: https://geh.darshan09200.dev/docs/examples/advanced-examples Shows how to automatically chain native exception handlers. By setting `callPreviouslyDefinedHandler: true` in the options, the library will invoke any previously defined native exception handlers. ```javascript setNativeExceptionHandler((errorString) => { console.log('Native error:', errorString); }, { callPreviouslyDefinedHandler: true }); ``` -------------------------------- ### Set Up JS and Native Exception Handlers (JavaScript) Source: https://geh.darshan09200.dev/docs/examples/basic-examples Configures global exception handlers for both JavaScript and native errors. The JS handler displays an alert for fatal errors and logs non-fatal ones. The native handler logs the error string and optionally forces the app to quit on Android. ```javascript import { setJSExceptionHandler, setNativeExceptionHandler } from 'react-native-global-exception-handler'; import { Alert, Platform } from 'react-native'; setJSExceptionHandler((error, isFatal) => { if (isFatal) { Alert.alert('Unexpected Error', `${error.name}: ${error.message}`, [{ text: 'OK' }]); } else { console.warn('Non-fatal JS error', error); } }, true); setNativeExceptionHandler((errorString) => { console.log('Native Exception:', errorString); }, { forceAppToQuit: Platform.OS === 'android', callPreviouslyDefinedHandler: false }); ``` -------------------------------- ### Chain JS Exception Handlers Source: https://geh.darshan09200.dev/docs/examples/advanced-examples Demonstrates how to chain a new JavaScript exception handler with an existing one. It retrieves the previous handler using `getJSExceptionHandler` and calls it after executing custom logic. ```javascript import { setJSExceptionHandler, getJSExceptionHandler } from 'react-native-global-exception-handler'; const previousHandler = getJSExceptionHandler(); setJSExceptionHandler((error, isFatal) => { // Custom logic console.log('Custom JS handler', error.message); // Call previous if exists if (previousHandler) previousHandler(error, isFatal); }, true); ``` -------------------------------- ### Deprecated Positional Native API Usage (JavaScript) Source: https://geh.darshan09200.dev/docs/examples/basic-examples Shows the deprecated way of configuring the native exception handler using positional arguments. While it still functions, using the object form for options is recommended for clarity and future compatibility. ```javascript // Still works but not recommended setNativeExceptionHandler(handlerFn, true, false); ``` -------------------------------- ### Integrate Sentry with react-native-global-exception-handler Source: https://geh.darshan09200.dev/docs/examples/analytics-integration This snippet shows how to integrate Sentry with react-native-global-exception-handler to capture both JavaScript and native exceptions. It assumes Sentry SDK is installed and initialized. JavaScript errors are captured with their fatal status, while native errors are reported as fatal. ```javascript import * as Sentry from '@sentry/react-native'; import { setJSExceptionHandler, setNativeExceptionHandler } from 'react-native-global-exception-handler'; // JavaScript exceptions setJSExceptionHandler((error, isFatal) => { Sentry.captureException(error, { level: isFatal ? 'fatal' : 'error', tags: { error_type: 'javascript', is_fatal: isFatal } }); }, true); // Native exceptions setNativeExceptionHandler((errorString) => { Sentry.captureMessage(errorString, { level: 'fatal', tags: { error_type: 'native' } }); }); ``` -------------------------------- ### Prevent App Quit on Native Crash (Android) Source: https://geh.darshan09200.dev/docs/examples/advanced-examples Configures the native exception handler to prevent the app from automatically quitting after a native crash on Android. This is useful in rare scenarios where app recovery might be attempted, though stability is not guaranteed. ```javascript setNativeExceptionHandler((errorString) => { console.log('Attempting recovery after native crash'); // Limited operations; app state may be unstable }, { forceAppToQuit: false }); ``` -------------------------------- ### Build Production Release Bundles for iOS and Android Source: https://geh.darshan09200.dev/docs/advanced/testing These commands demonstrate how to build production release bundles for both iOS and Android using different package managers (npm, Yarn, pnpm, Bun). This is necessary to test native exception handling, as it is not active in development mode. ```bash # iOS npx react-native run-ios --configuration Release # Android npx react-native run-android --variant=release ``` ```bash # iOS yarn dlx react-native run-ios --configuration Release # Android npx react-native run-android --variant=release ``` ```bash # iOS pnpm dlx react-native run-ios --configuration Release # Android npx react-native run-android --variant=release ``` ```bash # iOS bun x react-native run-ios --configuration Release # Android npx react-native run-android --variant=release ``` -------------------------------- ### Run Android Release Build for Native Handler Testing (Bun) Source: https://geh.darshan09200.dev/docs/troubleshooting Command to run the Android application in release mode using Bun, necessary for testing native exception handling. ```bash bun x react-native run-android --variant=release ``` -------------------------------- ### Clean and Rebuild iOS/Android for TurboModule Errors (Bun) Source: https://geh.darshan09200.dev/docs/troubleshooting Commands to clean iOS pods and Android Gradle, then rebuild the application using Bun to fix TurboModule errors. ```bash # iOS cd ios && rm -rf Pods && pod install && cd .. bun x react-native run-ios # Android cd android && ./gradlew clean && cd .. npx react-native run-android ``` -------------------------------- ### Clean and Rebuild iOS/Android for TurboModule Errors (npm) Source: https://geh.darshan09200.dev/docs/troubleshooting Commands to clean iOS pods and Android Gradle, then rebuild the application using npm to resolve TurboModule errors. ```bash # iOS cd ios && rm -rf Pods && pod install && cd .. npx react-native run-ios # Android cd android && ./gradlew clean && cd .. npx react-native run-android ``` -------------------------------- ### Run Android Release Build for Native Handler Testing (pnpm) Source: https://geh.darshan09200.dev/docs/troubleshooting Command to run the Android application in release mode using pnpm, required for testing native exception handlers. ```bash pnpm dlx react-native run-android --variant=release ``` -------------------------------- ### Run Android Release Build for Native Handler Testing (npm) Source: https://geh.darshan09200.dev/docs/troubleshooting Command to run the Android application in release mode using npm, necessary for testing native exception handling which may not work in debug builds. ```bash npx react-native run-android --variant=release ``` -------------------------------- ### Clean and Rebuild iOS/Android for TurboModule Errors (pnpm) Source: https://geh.darshan09200.dev/docs/troubleshooting Commands to clean iOS pods and Android Gradle, then rebuild the application using pnpm to resolve TurboModule errors. ```bash # iOS cd ios && rm -rf Pods && pod install && cd .. pnpm dlx react-native run-ios # Android cd android && ./gradlew clean && cd .. npx react-native run-android ``` -------------------------------- ### Set Up JavaScript and Native Exception Handlers in TypeScript Source: https://geh.darshan09200.dev/index This snippet demonstrates how to set up both JavaScript and native exception handlers using the react-native-global-exception-handler library. It shows the basic usage of `setJSExceptionHandler` and `setNativeExceptionHandler` for reporting errors and handling native crashes. ```typescript import { setJSExceptionHandler, setNativeExceptionHandler, } from 'react-native-global-exception-handler'; setJSExceptionHandler((err, fatal) => { // report + graceful UI }, true); setNativeExceptionHandler(msg => { // send to analytics }); ``` -------------------------------- ### Enable Hermes Engine for iOS Source: https://geh.darshan09200.dev/docs/troubleshooting Shows the configuration change required in the `ios/Podfile` to enable the Hermes JavaScript engine, which is necessary for certain features of the exception handler library. ```ruby use_react_native!( :path => config[:reactNativePath], :hermes_enabled => true ) ``` -------------------------------- ### Clean and Rebuild iOS/Android for TurboModule Errors (Yarn) Source: https://geh.darshan09200.dev/docs/troubleshooting Commands to clean iOS pods and Android Gradle, then rebuild the application using Yarn to fix TurboModule errors. ```bash # iOS cd ios && rm -rf Pods && pod install && cd .. yarn dlx react-native run-ios # Android cd android && ./gradlew clean && cd .. npx react-native run-android ``` -------------------------------- ### Get Current JavaScript Exception Handler Source: https://geh.darshan09200.dev/docs/usage/usage Retrieves the currently configured global JavaScript exception handler. This function can be useful for inspecting the active handler or for advanced scenarios where you might need to interact with the existing handler. ```javascript import { getJSExceptionHandler } from 'react-native-global-exception-handler'; const currentHandler = getJSExceptionHandler(); ``` -------------------------------- ### Clean Android Gradle Cache Source: https://geh.darshan09200.dev/docs/troubleshooting Commands to clean the Android project's Gradle cache and perform a clean build, often resolving build issues. ```bash cd android ./gradlew clean ./gradlew cleanBuildCache cd .. ``` -------------------------------- ### Reset Metro Cache for TurboModule Errors (Bun) Source: https://geh.darshan09200.dev/docs/troubleshooting Command to reset the Metro bundler cache using Bun, helpful for 'TurboModule Not Found' issues. ```bash bun x react-native start --reset-cache ``` -------------------------------- ### Upgrade React Native for Compatibility Source: https://geh.darshan09200.dev/docs/troubleshooting Provides commands to upgrade React Native using different package managers (npm, Yarn, pnpm, Bun) to meet the `react-native-global-exception-handler`'s version requirement of 0.68+. ```bash npx react-native upgrade ``` ```bash yarn dlx react-native upgrade ``` ```bash pnpm dlx react-native upgrade ``` ```bash bun x react-native upgrade ``` -------------------------------- ### Run Android Release Build for Native Handler Testing (Yarn) Source: https://geh.darshan09200.dev/docs/troubleshooting Command to run the Android application in release mode using Yarn, essential for verifying native exception handler functionality. ```bash yarn dlx react-native run-android --variant=release ``` -------------------------------- ### Enable Hermes Engine for Android Source: https://geh.darshan09200.dev/docs/troubleshooting Provides the configuration setting in `android/app/build.gradle` to enable the Hermes JavaScript engine for Android applications, a requirement for some functionalities of the exception handler library. ```gradle project.ext.react = [ enableHermes: true ] ``` -------------------------------- ### Configure `forceAppToQuit: true` for Android Native Handler Source: https://geh.darshan09200.dev/docs/troubleshooting JavaScript code snippet demonstrating how to configure the native exception handler on Android with `forceAppToQuit: true` to ensure the app quits properly after an error. ```javascript setNativeExceptionHandler((errorString) => { // Handle error }, { forceAppToQuit: true // Required for proper cleanup }); ``` -------------------------------- ### Update Native Handler Usage: JavaScript Source: https://geh.darshan09200.dev/docs/migration/migrating-from-react-native-exception-handler Shows the transition from the legacy positional arguments to the recommended options object for setting the native exception handler. ```javascript // Before setNativeExceptionHandler(handler, true, false); // After setNativeExceptionHandler(handler, { forceAppToQuit: true, callPreviouslyDefinedHandler: false }); ``` -------------------------------- ### Reset Metro Cache for TurboModule Errors (pnpm) Source: https://geh.darshan09200.dev/docs/troubleshooting Command to reset the Metro bundler cache using pnpm, addressing 'TurboModule Not Found' errors. ```bash pnpm dlx react-native start --reset-cache ``` -------------------------------- ### Configure `forceAppToQuit: false` for Navigation Libraries Source: https://geh.darshan09200.dev/docs/troubleshooting JavaScript code snippet showing how to set `forceAppToQuit: false` in the native exception handler configuration. This is useful when using navigation libraries that manage app state after errors. ```javascript setNativeExceptionHandler((errorString) => { // Log error for debugging console.log('Native error:', errorString); // Send to analytics reportToAnalytics(errorString); }, { forceAppToQuit: false, // Let the navigation library handle recovery callPreviouslyDefinedHandler: true // Chain with navigation's handler }); ``` -------------------------------- ### React Native: Simulate Native Crashes for Testing Source: https://geh.darshan09200.dev/docs/advanced/customization This JavaScript code snippet demonstrates how to use the `react-native-global-exception-handler` library to simulate different types of native crashes. This is crucial for testing the robustness of your custom error handling implementation across various failure scenarios. ```javascript import { simulateNativeCrash, CrashType } from 'react-native-global-exception-handler'; // Test different crash types simulateNativeCrash(CrashType.array_bounds); simulateNativeCrash(CrashType.memory_access); ``` -------------------------------- ### Guard Crash Simulation with __DEV__ Source: https://geh.darshan09200.dev/docs/advanced/testing This best practice snippet shows how to conditionally enable crash simulation using the `__DEV__` global variable. This ensures that crash simulation code is only executed in development builds, preventing accidental production crashes. ```javascript if (__DEV__) { global.simulateCrash = () => { simulateNativeCrash('nsexception'); }; } ``` -------------------------------- ### Reset Metro Cache for TurboModule Errors (Yarn) Source: https://geh.darshan09200.dev/docs/troubleshooting Command to reset the Metro bundler cache using Yarn, useful for resolving 'TurboModule Not Found' errors. ```bash yarn dlx react-native start --reset-cache ``` -------------------------------- ### Optimize Exception Handlers for Performance Source: https://geh.darshan09200.dev/docs/troubleshooting Compares a bad practice of performing heavy synchronous operations within an exception handler to a good practice of using asynchronous operations like `setTimeout` to queue tasks for later processing, thus improving app performance. ```javascript // ❌ Bad - Heavy synchronous operation setJSExceptionHandler((error, isFatal) => { // Expensive operation const largeData = processHugeDataset(); sendToServer(largeData); }, true); // ✅ Good - Async operation setJSExceptionHandler((error, isFatal) => { // Queue for later processing setTimeout(() => { sendToServer(error); }, 0); }, true); ``` -------------------------------- ### Enable Debug Mode with JS and Native Exception Handling Source: https://geh.darshan09200.dev/docs/troubleshooting This code enables debug mode for enhanced troubleshooting. It sets up both JavaScript and native exception handlers. The JS handler logs detailed error information, while the native handler logs any native exceptions encountered. This requires adding the code to your `index.js` file. ```javascript if (__DEV__) { console.log('Global Exception Handler - Debug Mode'); setJSExceptionHandler((error, isFatal) => { console.log('=== JS Exception Caught ==='); console.log('Fatal:', isFatal); console.log('Error:', error); console.log('Stack:', error.stack); console.log('=========================='); }, true); setNativeExceptionHandler((errorString) => { console.log('=== Native Exception Caught ==='); console.log('Error:', errorString); console.log('==============================='); }); } ``` -------------------------------- ### Reset Metro Cache for TurboModule Errors (npm) Source: https://geh.darshan09200.dev/docs/troubleshooting Command to reset the Metro bundler cache using npm, which can resolve 'TurboModule Not Found' errors in React Native's new architecture. ```bash npx react-native start --reset-cache ``` -------------------------------- ### Queue Errors Locally with Async Storage Source: https://geh.darshan09200.dev/docs/troubleshooting This snippet demonstrates how to queue errors locally using AsyncStorage when they are captured but not sent to the analytics service. It ensures errors are not lost due to network issues. ```javascript import AsyncStorage from '@react-native-async-storage/async-storage'; const queueError = async (error) => { const queue = await AsyncStorage.getItem('error_queue'); const errors = queue ? JSON.parse(queue) : []; errors.push(error); await AsyncStorage.setItem('error_queue', JSON.stringify(errors)); }; setJSExceptionHandler((error, isFatal) => { queueError({ error, isFatal }); }, true); ``` -------------------------------- ### Set Native Exception Handler - Basic Usage (JavaScript) Source: https://geh.darshan09200.dev/docs/usage/native-crash-handling Sets up a global handler for native exceptions. The provided callback function receives the native error message or stack trace. It's recommended to report these errors to a monitoring service. ```javascript import { setNativeExceptionHandler } from 'react-native-global-exception-handler'; setNativeExceptionHandler((errorString) => { // errorString contains the native error message/stack console.log('Native crash:', errorString); // Send to error monitoring reportToSentry(errorString); }); ``` -------------------------------- ### Conditionally Simulate Native Crash on iOS/Android Source: https://geh.darshan09200.dev/docs/troubleshooting This code checks the platform before attempting to simulate a native crash, ensuring it only runs on iOS or Android devices/simulators. It prevents errors on unsupported platforms like web. ```javascript import { Platform } from 'react-native'; if (Platform.OS === 'ios' || Platform.OS === 'android') { simulateNativeCrash('nsexception'); } else { console.log('Not supported on this platform'); } ``` -------------------------------- ### Android: Create and Register Custom Error Activity Source: https://geh.darshan09200.dev/docs/advanced/customization Replace the default native error screen with a custom `Activity` by creating `CustomErrorActivity.kt` and its layout file `activity_custom_error.xml`. Register this activity in `MainApplication.kt` using `replaceErrorScreenActivityClass` and declare it in `AndroidManifest.xml`. ```kotlin // CustomErrorActivity.kt import android.app.Activity import android.os.Bundle import android.widget.Button import android.widget.TextView import android.content.Intent class CustomErrorActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_custom_error) // Get error message from intent val errorMessage = intent.getStringExtra("error") findViewById(R.id.errorText).text = errorMessage findViewById