Hi there, I want to ask a question, is there’s a w...
# koin-contributors
b
Hi there, I want to ask a question, is there’s a way to catch an exception that happen during creation of an object inside
single{}
? The reason I’m asking this is because when creating
EncryptedSharedPreferences
object using
single{}
, sometimes it’s throw an Exception, and I want to catch that, prevent the crash app on user side, thanks
g
I think #koin is better suited for this question. Do you have a fallback object to prevent crashing? You can do something like
Copy code
single<EncryptedSharedPreferences?> {
     runCatching { 
         // Create object
     }.getOrNull()
}
Never tried koin with nullable objects but I don't see a reason not to work. I would suggest to think it through though as not crashing means that you can't make any assumptions that the object exists thoughout the app, meaning crashing might be the best course of action. The other alternative is to create a "factory" that catches the exception and provides an alternative object.
b
ok then, I’ll try to ask that channel, thanks yes I have a fallback object, the code I want to reach is simillar as below
Copy code
single<SharedPreferences> {
    try {
        //return EncryptedSharedPreference object
    } catch (e: Exception) {
        //Send to firebase crashlytics
        //return SharedPreference object
    }
}
I think it’s the same rather make it return
null
or
SharedPreference
object, it’s prevent the crash though. Yeah I already think of it thoroughly, because the code is fine, but the library itself is the problem, AFAIK, thanks
The other alternative is to create a “factory” that catches the exception and provides an alternative object.
what’s the difference using
factory
and
single
? I don’t see any difference
g
I wasn't talking about a koin factory or not using "single". I was just saying to abstract it away into a method or class that creates the object instead of having it directly into the single's lamda. But that has nothing to do with your issue
b
Sorry for my misunderstanding then. Though your suggestion not relate to my issue, it still a nice idea, thanks
👍 1
I ended up doing like below thought
Copy code
fun provideEncryptedSharedPreference(): SharedPreferences? {
        return try {
            EncryptedSharedPreferences.create()
        } catch (e: Exception) {
            null
        }
    }

    single() {
        return@single provideEncryptedSharedPreference()
    }

    single() {
        //instantiate helper class
        Helper(getOrNull())
    }
since
runCatching
can’t add firebase crashlytics record exception in it’s
catch
. still want to record the exception in case some other exception happens