I have a question regarding the Koin handling exception.
In a module where I defined EncryptedSharedPreferences.create()
, sometimes causing an exception, which results in a crash in the user's device. I see in the crashlytic report that the crash already happens over 200 times. More specific exception is below.
Caused by java.security.UnrecoverableKeyException: Failed to obtain information about key
...
Caused by android.security.KeyStoreException: -49
Apparently, this issue is already reported, yet there's no valid answer to handle or solving it. Because I'm using Koin to define the EncryptedSharedPreferences
, I thought it's better to handle it inside single{}
function. Put a try catch
that will catch the exception. But when I try to throw an Exception
inside try, it didn't catch the Exception, it's just crash, not what I expecting. The code looks like below
single(named(ENCRYPTED_SHARED_PREF)) {
val context = androidApplication().applicationContext
try {
val masterKey =
MasterKey.Builder(context, MasterKey.DEFAULT_MASTER_KEY_ALIAS)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build()
EncryptedSharedPreferences.create(
context,
SP_ENCRYPTED_KEY,
masterKey,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
throwError()
} catch (e: Exception) {
Timber.d("[SHARED PREF] Terjadi exception")
when (e) {
is KeyStoreException -> {
Toast.makeText(context, "Terjadi exception", Toast.LENGTH_SHORT).show()
}
}
//Update missing link below
androidApplication().getSharedPreferences(SP_KEY, Context.MODE_PRIVATE)
}
}
...
@Throws(KeyStoreException::class)
fun throwError(): Nothing {
throw KeyStoreException("Terjadi exception")
}
Now for the question, is there's a way to handle this kind of Exception inside Koin single
or not? I had try to search for the documentation and google it, seems a dead end to me.
Other useful information:
EncryptedSharedPreferences
version :androidx.security:security-crypto:1.1.0-alpha03
- Issue tracker for
EncryptedSharedPreferences
I faced : https://issuetracker.google.com/u/1/issues/167977579 - The crash or exception not related to Koin issue, rather it's on
EncryptedSharedPreferences
- Koin version :
org.koin:koin-android-viewmodel:2.1.6
UPDATE SOLVE
Took me a while to realize that the catch
block needs to return something such as a value or another object, let say normally shared preference. Nothing wrong with the code thought after in-depth research. Thanks all, I also update the code in my explanation above.