invertase / react-native-firebase

πŸ”₯ A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
https://rnfirebase.io
Other
11.68k stars 2.21k forks source link

πŸ”₯[πŸ›] Bug Report Title - iOS + Android - Non-fatal reports are not being sent #6542

Closed Czino closed 1 year ago

Czino commented 2 years ago

Issue

We want our users to opt into sending crash reports. So I've been trying to send non-fatal reports from the app while crashlytics_auto_collection_enabled is set to false

After a non-fatal error, we log the error via crashlytics().recordError(err) and we then display a prompt to the user asking for permission, if yes then we execute crashlytics().sendUnsentReports()

This seems to be working only on iOS, no reports are being sent from Android.

After reading up and learning, that reports are only packaged after crashes or restarts of the app, I restructured our code to check for unsent reports

 // check if app has crashed and ask for permission to send crash report
if (await await crashlytics().didCrashOnPreviousExecution()
  || await crashlytics().checkForUnsentReports()) openCrashReportPrompt()

At this point, even after forcing JS errors, the condition is never true, the crashReportPrompt never opens. Even running crashlytics().sendUnsentReports() anyways has no result.

Running the adb log gives me the following when calling crashlytics().recordError(err) There are no logs for sendUnsentReports()

09-16 01:49:49.936 20391 23525 D RNFBCrashlyticsInit: isCrashlyticsCollectionEnabled final value: false
09-16 01:49:49.936 20391 23525 I Crashlytics: crashlytics collection is not enabled, not crashing.

Describe your issue here


Project Files

Javascript

Click To Expand

#### `package.json`: ```json ... "@react-native-firebase/analytics": "^14.11.1", "@react-native-firebase/app": "^14.11.1", "@react-native-firebase/crashlytics": "^14.11.1", "@react-native-firebase/messaging": "^14.11.1", ... ``` #### `firebase.json` for react-native-firebase v6: ```json { "react-native": { "crashlytics_auto_collection_enabled": false, "crashlytics_debug_enabled": true, "crashlytics_ndk_enabled": true, "crashlytics_is_error_generation_on_js_crash_enabled": true, "crashlytics_javascript_exception_handler_chaining_enabled": true, "analytics_auto_collection_enabled": false, "messaging_android_notification_color": "@color/orange" } } ```

iOS

Click To Expand

#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like: ```ruby $RNFirebaseAnalyticsWithoutAdIdSupport=true require_relative '../node_modules/react-native/scripts/react_native_pods' require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules' platform :ios, '12.0' install! 'cocoapods', :deterministic_uuids => false abstract_target 'appname' do config = use_native_modules! # Flags change depending on the env values. flags = get_default_flags() use_react_native!( :path => config[:reactNativePath], # to enable hermes on iOS, change `false` to `true` and then install pods :hermes_enabled => flags[:hermes_enabled], :fabric_enabled => flags[:fabric_enabled], # An absolute path to your application root. :app_path => "#{Pod::Config.instance.installation_root}/.." ) # pod 'react-native-document-picker', :path => '../node_modules/react-native-document-picker' # pod 'RNFS', :path => '../node_modules/react-native-fs' pod 'RNScreens', :path => '../node_modules/react-native-screens' pod 'react-native-fast-openpgp', :path => '../node_modules/react-native-fast-openpgp' pod 'react-native-camera', :path => '../node_modules/react-native-camera' pod 'RNPermissions', :path => '../node_modules/react-native-permissions' pod 'Permission-Camera', :path => "../node_modules/react-native-permissions/ios/Camera" pod 'RNGestureHandler', :path => '../node_modules/react-native-gesture-handler' target 'mainnet' do inherit! :complete # Pods for testnet end target 'testnet' do inherit! :complete # Pods for testnet end target 'Tests' do inherit! :complete # Pods for testing end # Enables Flipper. # # Note that if you have use_frameworks! enabled, Flipper will not work and # you should disable the next line. use_flipper!() post_install do |installer| react_native_post_install(installer) __apply_Xcode_12_5_M1_post_install_workaround(installer) end end ``` #### `AppDelegate.m`: ```objc #import "RNFBMessagingModule.h" #import #import "AppDelegate.h" #import #import #import #import #if RCT_NEW_ARCH_ENABLED #import #import #import #import #import #import #import @interface AppDelegate () { RCTTurboModuleManager *_turboModuleManager; RCTSurfacePresenterBridgeAdapter *_bridgeAdapter; std::shared_ptr _reactNativeConfig; facebook::react::ContextContainer::Shared _contextContainer; } @end #endif @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [FIRApp configure]; RCTAppSetupPrepareApp(application); RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions]; #if RCT_NEW_ARCH_ENABLED _contextContainer = std::make_shared(); _reactNativeConfig = std::make_shared(); _contextContainer->insert("ReactNativeConfig", _reactNativeConfig); _bridgeAdapter = [[RCTSurfacePresenterBridgeAdapter alloc] initWithBridge:bridge contextContainer:_contextContainer]; bridge.surfacePresenter = _bridgeAdapter.surfacePresenter; #endif UIView *rootView = RCTAppSetupDefaultRootView(bridge, @"appname", nil); if (@available(iOS 13.0, *)) { rootView.backgroundColor = [UIColor systemBackgroundColor]; } else { rootView.backgroundColor = [UIColor whiteColor]; } self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; UIViewController *rootViewController = [UIViewController new]; rootViewController.view = rootView; self.window.rootViewController = rootViewController; [self.window makeKeyAndVisible]; return YES; } - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge { #if DEBUG return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"]; #else return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; #endif } #if RCT_NEW_ARCH_ENABLED #pragma mark - RCTCxxBridgeDelegate - (std::unique_ptr)jsExecutorFactoryForBridge:(RCTBridge *)bridge { _turboModuleManager = [[RCTTurboModuleManager alloc] initWithBridge:bridge delegate:self jsInvoker:bridge.jsCallInvoker]; return RCTAppSetupDefaultJsExecutorFactory(bridge, _turboModuleManager); } #pragma mark RCTTurboModuleManagerDelegate - (Class)getModuleClassFromName:(const char *)name { return RCTCoreModulesClassProvider(name); } - (std::shared_ptr)getTurboModule:(const std::string &)name jsInvoker:(std::shared_ptr)jsInvoker { return nullptr; } - (std::shared_ptr)getTurboModule:(const std::string &)name initParams: (const facebook::react::ObjCTurboModule::InitParams &)params { return nullptr; } - (id)getModuleInstanceFromClass:(Class)moduleClass { return RCTAppSetupDefaultModuleFromClass(moduleClass); } #endif @end ```


Android

Click To Expand

#### Have you converted to AndroidX? - [ ] my application is an AndroidX application? - [ ] I am using `android/gradle.settings` `jetifier=true` for Android compatibility? - [ ] I am using the NPM package `jetifier` for react-native compatibility? #### `android/build.gradle`: ```groovy // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext { buildToolsVersion = "31.0.0" minSdkVersion = 28 compileSdkVersion = 31 targetSdkVersion = 31 ndkVersion = "21.4.7075529" } repositories { google() mavenCentral() } dependencies { classpath("com.android.tools.build:gradle:7.0.4") classpath("com.facebook.react:react-native-gradle-plugin") classpath("de.undercouch:gradle-download-task:4.1.2") classpath 'com.google.gms:google-services:4.3.10' classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url("$rootDir/../node_modules/react-native/android") } maven { // Android JSC is installed from npm url("$rootDir/../node_modules/jsc-android/dist") } mavenCentral { // We don't want to fetch react-native from Maven Central as there are // older versions over there. content { excludeGroup "com.facebook.react" } } google() maven { url 'https://www.jitpack.io' } } } ``` #### `android/app/build.gradle`: ```groovy apply plugin: "com.android.application" apply plugin: 'com.google.gms.google-services' apply plugin: 'com.google.firebase.crashlytics' import com.android.build.OutputFile /** * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets * and bundleReleaseJsAndAssets). * These basically call `react-native bundle` with the correct arguments during the Android build * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the * bundle directly from the development server. Below you can see all the possible configurations * and their defaults. If you decide to add a configuration block, make sure to add it before the * `apply from: "../../node_modules/react-native/react.gradle"` line. * * project.ext.react = [ * // the name of the generated asset file containing your JS bundle * bundleAssetName: "index.android.bundle", * * // the entry file for bundle generation. If none specified and * // "index.android.js" exists, it will be used. Otherwise "index.js" is * // default. Can be overridden with ENTRY_FILE environment variable. * entryFile: "index.android.js", * * // https://reactnative.dev/docs/performance#enable-the-ram-format * bundleCommand: "ram-bundle", * * // whether to bundle JS and assets in debug mode * bundleInDebug: false, * * // whether to bundle JS and assets in release mode * bundleInRelease: true, * * // whether to bundle JS and assets in another build variant (if configured). * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants * // The configuration property can be in the following formats * // 'bundleIn${productFlavor}${buildType}' * // 'bundleIn${buildType}' * // bundleInFreeDebug: true, * // bundleInPaidRelease: true, * // bundleInBeta: true, * * // whether to disable dev mode in custom build variants (by default only disabled in release) * // for example: to disable dev mode in the staging build type (if configured) * devDisabledInStaging: true, * // The configuration property can be in the following formats * // 'devDisabledIn${productFlavor}${buildType}' * // 'devDisabledIn${buildType}' * * // the root of your project, i.e. where "package.json" lives * root: "../../", * * // where to put the JS bundle asset in debug mode * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", * * // where to put the JS bundle asset in release mode * jsBundleDirRelease: "$buildDir/intermediates/assets/release", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in debug mode * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in release mode * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", * * // by default the gradle tasks are skipped if none of the JS files or assets change; this means * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to * // date; if you have any other folders that you want to ignore for performance reasons (gradle * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ * // for example, you might want to remove it from here. * inputExcludes: ["android/**", "ios/**"], * * // override which node gets called and with what additional arguments * nodeExecutableAndArgs: ["node"], * * // supply additional arguments to the packager * extraPackagerArgs: [] * ] */ def environment = 'development' def myExtraPackagerArgs = ['--dev', 'true'] if (System.getenv('NODE_ENV').toString()) { environment = System.getenv('NODE_ENV').toString() } if (System.getenv('dev').toString() == 'false') { environment = 'production' } if (environment == 'production') { myExtraPackagerArgs = ['--dev', 'false'] } println 'Build environment: ' + environment project.ext.react = [ enableHermes: false, // clean and rebuild if changing bundleInDebug: true, bundleInStaging: true, extraPackagerArgs: myExtraPackagerArgs ] if (environment == 'production') { apply from: "../../node_modules/react-native/react.gradle" } /** * Set this to true to create two separate APKs instead of one: * - An APK that only works on ARM devices * - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */ def enableSeparateBuildPerCPUArchitecture = true /** * Run Proguard to shrink the Java bytecode in release builds. */ def enableProguardInReleaseBuilds = true /** * The preferred build flavor of JavaScriptCore. * * For example, to use the international variant, you can use: * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that * give correct results when using with locales other than en-US. Note that * this variant is about 6MiB larger per architecture than default. */ def jscFlavor = 'org.webkit:android-jsc:+' /** * Whether to enable the Hermes VM. * * This should be set on project.ext.react and mirrored here. If it is not set * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode * and the benefits of using Hermes will therefore be sharply reduced. */ def enableHermes = project.ext.react.get("enableHermes", false); android { ndkVersion rootProject.ext.ndkVersion compileSdkVersion rootProject.ext.compileSdkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { applicationId "com.APPBUNDLEID" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 77 versionName "0.1.3" missingDimensionStrategy 'react-native-camera', 'general' multiDexEnabled true } splits { abi { reset() enable enableSeparateBuildPerCPUArchitecture universalApk true // If true, also generate a universal APK include "armeabi-v7a", "x86", "arm64-v8a", "x86_64" } } signingConfigs { debug { storeFile file(MYAPP_RELEASE_STORE_FILE) storePassword MYAPP_RELEASE_STORE_PASSWORD keyAlias MYAPP_RELEASE_KEY_ALIAS keyPassword MYAPP_RELEASE_KEY_PASSWORD } } buildTypes { debug { signingConfig signingConfigs.debug } release { // Caution! In production, you need to generate your own keystore file. // see https://reactnative.dev/docs/signed-apk-android. signingConfig signingConfigs.debug minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" firebaseCrashlytics { nativeSymbolUploadEnabled true unstrippedNativeLibsDir 'build/intermediates/merged_native_libs/release/out/lib' } } } flavorDimensions ("environment") productFlavors { qa { dimension "environment" applicationIdSuffix "" } prod { dimension "environment" applicationIdSuffix ".mainnet" } } // applicationVariants are e.g. debug, release applicationVariants.all { variant -> variant.outputs.each { output -> // For each separate APK per architecture, set a unique version code as described here: // https://developer.android.com/studio/build/configure-apk-splits.html // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc. def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4] def abi = output.getFilter(OutputFile.ABI) if (abi != null) { // null for the universal-debug, universal-release variants output.versionCodeOverride = defaultConfig.versionCode * 1000 + versionCodes.get(abi) } } } } dependencies { implementation fileTree(dir: "libs", include: ["*.jar"]) //noinspection GradleDynamicVersion implementation "com.facebook.react:react-native:+" // From node_modules implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0" debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") { exclude group:'com.facebook.fbjni' } debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") { exclude group:'com.facebook.flipper' exclude group:'com.squareup.okhttp3', module:'okhttp' } debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") { exclude group:'com.facebook.flipper' } if (enableHermes) { def hermesPath = "../../node_modules/hermes-engine/android/"; debugImplementation files(hermesPath + "hermes-debug.aar") releaseImplementation files(hermesPath + "hermes-release.aar") } else { implementation jscFlavor } implementation platform('com.google.firebase:firebase-bom:29.2.1') implementation 'com.google.firebase:firebase-messaging' implementation 'com.google.firebase:firebase-analytics' } // Run this once to be able to run the application with BUCK // puts all compile dependencies into folder libs for BUCK to use task copyDownloadableDepsToLibs(type: Copy) { from configurations.implementation into 'libs' } apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project) ``` #### `android/settings.gradle`: ```groovy rootProject.name = 'projectname' include ':react-native-gesture-handler' project(':react-native-gesture-handler').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-gesture-handler/android') include ':react-native-permissions' project(':react-native-permissions').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-permissions/android') include ':react-native-camera' project(':react-native-camera').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-camera/android') include ':react-native-fast-openpgp' project(':react-native-fast-openpgp').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fast-openpgp/android') include ':react-native-screens' project(':react-native-screens').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-screens/android') include ':react-native-fs' project(':react-native-fs').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fs/android') include ':react-native-document-picker' project(':react-native-document-picker').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-document-picker/android') apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) include ':app' includeBuild('../node_modules/react-native-gradle-plugin') if (settings.hasProperty("newArchEnabled") && settings.newArchEnabled == "true") { include(":ReactAndroid") project(":ReactAndroid").projectDir = file('../node_modules/react-native/ReactAndroid') } ``` #### `MainApplication.java`: ```java package com.BUNDLEID; import android.app.Application; import android.content.Context; import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; import com.zoontek.rnpermissions.RNPermissionsPackage; import org.reactnative.camera.RNCameraPackage; import com.reactnativefastopenpgp.FastOpenpgpPackage; import com.swmansion.rnscreens.RNScreensPackage; import com.rnfs.RNFSPackage; import io.github.elyx0.reactnativedocumentpicker.DocumentPickerPackage; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.soloader.SoLoader; import java.lang.reflect.InvocationTargetException; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(new MyReactNativePackage()); return packages; } @Override protected String getJSMainModuleName() { return "index"; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); } /** * Loads Flipper in React Native templates. Call this in the onCreate method with something like * initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); * * @param context * @param reactInstanceManager */ private static void initializeFlipper( Context context, ReactInstanceManager reactInstanceManager) { if (BuildConfig.DEBUG) { try { /* We use reflection here to pick up the class that initializes Flipper, since Flipper library is not available in release mode */ Class aClass = Class.forName("com.BUNDLEID.ReactNativeFlipper"); aClass .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class) .invoke(null, context, reactInstanceManager); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } } ``` #### `AndroidManifest.xml`: ```xml ```


Environment

Click To Expand

**`react-native info` output:** ``` System: OS: macOS 12.5.1 CPU: (4) x64 Intel(R) Core(TM) i7-5557U CPU @ 3.10GHz Memory: 688.45 MB / 16.00 GB Shell: 3.2.57 - /bin/bash Binaries: Node: 16.14.2 - /usr/local/bin/node Yarn: Not Found npm: 8.12.1 - /usr/local/bin/npm Watchman: Not Found Managers: CocoaPods: 1.11.3 - /usr/local/bin/pod SDKs: iOS SDK: Platforms: DriverKit 21.4, iOS 15.5, macOS 12.3, tvOS 15.4, watchOS 8.5 Android SDK: API Levels: 23, 28, 29, 30, 31 Build Tools: 23.0.3, 24.0.2, 30.0.2, 31.0.0 System Images: android-23 | Intel x86 Atom, android-30 | Google APIs Intel x86 Atom, android-30 | Google APIs Intel x86 Atom_64, android-30 | Google Play Intel x86 Atom Android NDK: Not Found IDEs: Android Studio: 2021.1 AI-211.7628.21.2111.8309675 Xcode: 13.4.1/13F100 - /usr/bin/xcodebuild Languages: Java: 11.0.6 - /usr/bin/javac npmPackages: @react-native-community/cli: Not Found react: Not Found react-native: Not Found react-native-macos: Not Found npmGlobalPackages: *react-native*: Not Found ``` - **Platform that you're experiencing the issue on**: - [x] iOS - [x] Android - [ ] **iOS** but have not tested behavior on Android - [ ] **Android** but have not tested behavior on iOS - [x] Both - **`react-native-firebase` version you're using that has this issue:** - `e.g. 5.4.3` - **`Firebase` module(s) you're using that has the issue:** - `e.g. Instance ID` - **Are you using `TypeScript`?** - `Y` & `4.6.3`


mikehardy commented 2 years ago

Oh interesting - I suppose with recordError it's okay to queue the report, just not actually crash. This seems somewhat similar to another issue that is pending investigation - it's in the same area - #6479

Even stranger - I can understand your use case - but the behavior right now (do not record the error if collection is disabled) is supposed to be consistent on both platforms. You might check your iOS init sequence to see why the setting is not also denying reports on iOS, as the config flag is supposed to stop it there as well:

https://github.com/invertase/react-native-firebase/blob/3371727dd23976ce769696c71865460740502d80/packages/crashlytics/ios/RNFBCrashlytics/RNFBCrashlyticsModule.m#L163-L177

Changing this behavior might be considered a breaking change as it would potentially leak data from before a user gave permission if you record an error, the user denies permission, record another error, and the user grants permission. As a user I would expect the first error would not be recorded but if we altered the behavior as you request, it would record both then send both.

I do not think that is correct so I am not inclined to change the behavior.

It seems you must be modifying the exception handlers in order to detect the crash and prompt for user permission. Could you restructure to hold on to the error until the user grants permission, then if they do enable error collection and then record error?

That seems like it would match privacy expectations more closely

Czino commented 2 years ago

Okay, that makes sense not to change the underlying behaviour of the module.

I adapted our code to pass along errors to the prompt which calls this method to record the errors after enabling crashlytics collection. Because we want to ask our users after every unhandled error, we disable collection afterwards:

import crashlytics from '@react-native-firebase/crashlytics'
import { Alert } from 'react-native'
import i18n from '../i18n'
import { info } from '../log'
import { sleep } from '../performance'

const sendErrors = async (errors: Error[]) => {
  if (!crashlytics().isCrashlyticsCollectionEnabled) {
    info('Crashlytics not enabled yet, enable and wait 300ms')
    await crashlytics().setCrashlyticsCollectionEnabled(true)

    await sleep(300)
    sendErrors(errors)
    return
  }
  info('Crashlytics is enabled, sending crash reports')

  if (errors.length) {
    errors.forEach(err => {
      crashlytics().recordError(err)
    })
  } else {
    crashlytics().sendUnsentReports()
  }
  await crashlytics().setCrashlyticsCollectionEnabled(false)
}

export const openCrashReportPrompt = (errors: Error[]): void => {
  Alert.alert(
    i18n('crashReport.requestPermission.title'),
    [i18n('crashReport.requestPermission.description.1'), i18n('crashReport.requestPermission.description.2')].join(
      '\n\n',
    ),
    [
      {
        text: i18n('crashReport.requestPermission.deny'),
        onPress: () => {
          crashlytics().deleteUnsentReports()
        },
        style: 'default',
      },
      {
        text: i18n('crashReport.requestPermission.sendReport'),
        onPress: () => {
          sendErrors(errors)
        },
        style: 'default',
      },
    ],
  )
}

I am also performing a check on startup like this

// check if app has crashed and ask for permission to send crash report
if (await await crashlytics().didCrashOnPreviousExecution()
  || await crashlytics().checkForUnsentReports()) openCrashReportPrompt([])

I found 2 things

On a side note: I made sure that GoogleService-Info.plist and google-services.json are up to date


So I set "crashlytics_auto_collection_enabled": true inside firebase.json and voilΓ , crash reports are being sent. For the time being I use the code from above in a slimmed down version, and still keep the prompt. This way we can ask the user to report non-fatal unhandled errors. Fatal errors will now be automatically collected, for which I couldn't find a way asking for permission for each instance.

import { info } from '../log'
import { sleep } from '../performance'

const sendErrors = async (errors: Error[]) => {
  info('Sending crash reports')

  errors.forEach(err => {
    crashlytics().recordError(err)
  })
}
mikehardy commented 2 years ago

That is strange :thinking: - I'm not keen on changing the default behavior of the module and retaining data that may be sent in the future however it seems that:

1- if crashlytics_auto_collection_enabled was false to start in firebase.json 2- then you turn it on via await crashlytics().setCrashlyticsCollectionEnabled(true) 3- then you recordError 4- it should send a report

If I understand correctly, that's not happening? You never see a report unless firebase.json has a true for item 1 ?

And additionally item 2 does seem to have an effect, but is delayed vs expectations - that is it does change immediately but even with the await it returns a stale state for some amount of time afterwards?

Both of these seem like solve-able / not meeting API contract issues if I understand

Czino commented 2 years ago

If I understand correctly, that's not happening? You never see a report unless firebase.json has a true for item 1 ?

Yes, it seems that recording errors is not happening when crashlytics_auto_collection_enabled is false by default and setting it later to true via crashlytics().setCrashlyticsCollectionEnabled(true) to record an error right afterwards.

If it helps, the android logs sometimes (not always) still tell me the following despite checking crashlytics().isCrashlyticsCollectionEnabled being true

RNFBCrashlyticsInit: isCrashlyticsCollectionEnabled final value: false
Crashlytics: crashlytics collection is not enabled, not crashing.

There seems to be a discrepancy between the state the API tells me and the state in lower level code.

github-actions[bot] commented 1 year ago

Hello πŸ‘‹, to help manage issues we automatically close stale issues.

This issue has been automatically marked as stale because it has not had activity for quite some time.Has this issue been fixed, or does it still require attention?

This issue will be closed in 15 days if no further activity occurs.

Thank you for your contributions.

mikehardy commented 1 year ago

This needs attention I believe

github-actions[bot] commented 1 year ago

Hello πŸ‘‹, to help manage issues we automatically close stale issues.

This issue has been automatically marked as stale because it has not had activity for quite some time.Has this issue been fixed, or does it still require attention?

This issue will be closed in 15 days if no further activity occurs.

Thank you for your contributions.