-
Notifications
You must be signed in to change notification settings - Fork 3.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Exception handling when reading datastore. #1710
base: main
Are you sure you want to change the base?
Conversation
It would be great to add tests for this new code. |
I will try to add tests, though it seems that corrupting the file in unit test environment is challenging, maybe I might have to write androidTest. I will look into this. Thank you for your review. @SimonMarquis |
I'm not sure exactly how for now but I think you can fake the datastore and throw the IOException from the loading method. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice
Added unit tests by making fake datastore which throws exception while accessing. Then testing data source whether returning the default values or not. |
...t/kotlin/com/google/samples/apps/nowinandroid/core/datastore/NiaPreferencesDataSourceTest.kt
Outdated
Show resolved
Hide resolved
...t/kotlin/com/google/samples/apps/nowinandroid/core/datastore/NiaPreferencesDataSourceTest.kt
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM
@dturner |
If datastore isn't available, returning a default What am I missing? |
I think application will continuously crash on startUp if this exception unhandled. User may need to clear data forcefully, or uninstalled to recover from this unexpected situation. That's why I put the default UserPreferences and restored to something where user can fresh start using the app. |
@dturner it is not necessarily that "datastore" is not available, but rather that the datastore files are corrupted, and not recoverable. |
@dturner |
Thanks for the additional info, that makes sense. I'll need some time to consider the suggested approach before providing a review. Unfortunately I'm on vacation for a couple of weeks now so it'll likely be mid Jan 2025 now. |
What I have done and why
Datastore file can be corrupted in cases, or simply invalid. So there needs to handle runtime Fatal exception like I found:
FATAL EXCEPTION: main
Process: com.google.samples.apps.nowinandroid.demo.debug, PID: 10565
androidx.datastore.core.CorruptionException: Cannot read proto.
...
So exception handling is needed, and replaced with
UserPreferences.getDefaultInstance()
when there occurs such exception