1 package expo.modules.devlauncher.launcher.errors
2 
3 import android.content.Context
4 import android.content.SharedPreferences
5 import android.os.Bundle
6 import com.facebook.react.bridge.Arguments
7 import com.facebook.react.bridge.WritableMap
8 import com.google.gson.Gson
9 import expo.modules.devlauncher.launcher.DevLauncherRecentlyOpenedAppsRegistry
10 
11 private const val ERROR_REGISTRY_SHARED_PREFERENCES = "expo.modules.devlauncher.errorregistry"
12 private const val ERROR_REGISTRY_SHARED_PREFERENCES_KEY = "SavedError"
13 
14 data class DevLauncherErrorInstance(
15   val throwable: Throwable,
16   val timestamp: Long = DevLauncherRecentlyOpenedAppsRegistry.TimeHelper.getCurrentTime()
17 ) {
toWritableMapnull18   fun toWritableMap(): WritableMap? = Arguments.fromBundle(
19     Bundle().apply {
20       putLong("timestamp", timestamp)
21       putString("message", throwable.message ?: "Unknown")
22       putString("stack", throwable.stackTraceToString())
23     }
24   )
25 }
26 
27 class DevLauncherErrorRegistry(context: Context) {
28   private val sharedPreferences: SharedPreferences = context
29     .getSharedPreferences(
30       ERROR_REGISTRY_SHARED_PREFERENCES,
31       Context.MODE_PRIVATE
32     )
33 
storeExceptionnull34   fun storeException(throwable: Throwable) {
35     val errorInstance = DevLauncherErrorInstance(throwable)
36     val jsonString = Gson().toJson(errorInstance)
37 
38     sharedPreferences
39       .edit()
40       .putString(ERROR_REGISTRY_SHARED_PREFERENCES_KEY, jsonString)
41       .apply()
42   }
43 
consumeExceptionnull44   fun consumeException(): DevLauncherErrorInstance? {
45     val jsonString = sharedPreferences.getString(ERROR_REGISTRY_SHARED_PREFERENCES_KEY, null)
46       ?: return null
47 
48     try {
49       return Gson().fromJson(jsonString, DevLauncherErrorInstance::class.java)
50     } finally {
51       sharedPreferences
52         .edit()
53         .remove(ERROR_REGISTRY_SHARED_PREFERENCES_KEY)
54         .apply()
55     }
56   }
57 }
58