Catch and handle exceptions

Health Connect throws standard exceptions for CRUD operations when an issue is encountered. Your app should catch and handle each of these exceptions as appropriate.

Each method on HealthConnectClient lists the exceptions that can be thrown. In general, your app should handle the following exceptions:

Exception Description Recommended best practice
SecurityException There are issues encountered when the requests require permissions that aren't granted. To avoid this, make sure that you've requested the permissions for your published app. Also, these must be declared in the manifest file and in your activity.

IOException There are issues encountered upon reading and writing data from disk. To avoid this issue, here are some suggestions:

  • Back up any user input.
  • Be able to handle any issues that occur during bulk write operations. For example, make sure the process moves past the issue and carry out the remaining operations.
  • Apply retries and backoff strategies to handle request issues.

IllegalStateException One of the following scenarios has occurred:

  • The Health Connect service isn't available.
  • The request isn't a valid construction. For example, an aggregate request in periodic buckets where an Instant object is used for the timeRangeFilter.

Handle possible issues with the inputs first before doing a request. Preferably, assign values to variables or use them as parameters within a custom function instead of using them directly in your requests so that you can apply error handling strategies.
RemoteException Errors have occurred within, or in communicating with, the underlying service to which the SDK connects.

For example, your app is trying to delete a record with a given uid. However, the exception is thrown after the app finds out upon checking in the underlying service that the record doesn't exist.
To avoid this issue, here are some suggestions:

  • Perform regular syncs between your app's datastore and Health Connect.
  • Apply retries and backoff strategies to handle request issues.