Skip to content
CARP Docs
Ask AISystemLightDark
On this page

Error handling

How the plugin reports failures with HealthPlatformException and HealthErrorCode, and what each method does when it fails.

Copy MarkdownOpen inOpen in GitHubView as MarkdownOpen in Scira AIOpen in ChatGPTOpen in ClaudeOpen in Cursor

Read methods throw a HealthPlatformException when Health Connect or HealthKit reports an error. Its errorCode says what went wrong, and isRetryable says whether the same call may succeed later.

Before 14.0.0, Android reads returned an empty list or null on any failure, so a failed read looked like a time range without data. An empty result now means only that there is no data the app may read.

Exception types

ExceptionThrown when
HealthPlatformExceptionHealth Connect or HealthKit reports an error in a read: getHealthDataFromTypes(), getHealthDataPages(), getHealthDataByUUID(), getHealthIntervalDataFromTypes(), getTotalStepsInInterval(), getChangesToken() or getChanges().
HealthExceptionThe plugin itself rejects the call, for example for a data type that the platform or device does not have (notSupported).
PlatformExceptionA write, delete or permission method fails on the platform, for example with code INVALID_ARGUMENT for a sample that HealthKit does not accept.
UnsupportedErrorHealth Connect is not available, or the method does not exist on the platform, such as writeAudiogram() on Android. The message says why.
ArgumentErrorAn argument is not valid, for example WRITE access to a read-only type. Its subtype RangeError reports a pageSize or limit out of range.
MissingPluginExceptionThe platform has no implementation of the plugin or of the method, such as deleteByClientRecordId() on iOS. The plugin passes it on unchanged.

PlatformException and MissingPluginException come from package:flutter/services.dart.

Catch order

HealthPlatformException extends PlatformException, which iOS reads threw before 14.0.0, and implements HealthException. Handlers for either type therefore still catch it. To handle it on its own, catch it first:

try {
  final points = await health.getHealthDataFromTypes(types: types, startTime: start, endTime: end);
} on HealthPlatformException catch (e) {
  if (e.isRetryable) {
    // For example HealthErrorCode.rateLimitExceeded: try again later.
  } else if (e.errorCode == HealthErrorCode.permissionDenied) {
    // Ask for the permission.
  }
  // e.platformCode is the native code, e.details holds more information.
} on HealthException catch (e) {
  // For example a type that is not available on this platform (HealthErrorCode.notSupported).
}

Put on HealthPlatformException before on PlatformException and on HealthException: an earlier clause for either type catches it otherwise.

Both HealthException and HealthPlatformException have these properties:

PropertyTypeDescription
errorCodeHealthErrorCodeWhat went wrong. See Error codes.
isRetryableboolWhether the same call may succeed if the app makes it again later.
platformCodeString?The code that Health Connect or HealthKit reported, such as RATE_LIMIT_EXCEEDED, or null when the plugin raised the exception itself.
detailsObject?More information from the platform, or null. On Android, a map with the native exception class name and the healthConnectErrorCode, which is null before Android 14 and for errors without one. On iOS, a map with the error domain and its nativeCode.
dataTypedynamicThe data type, or the workout activity type, that the call failed for. It is null when getChangesToken() or getChanges() fails on the platform.
causeStringThe message of the platform or the plugin.

Error codes

HealthErrorCode says what went wrong. Each value has the platform code that the native side reports for it:

CodePlatform codeMeaningRetryable
rateLimitExceededRATE_LIMIT_EXCEEDEDThe app used up its Health Connect API quota. See Health Connect limits.Yes
permissionDeniedPERMISSION_DENIEDThe call needs a permission that the app does not have, for example READ_HEALTH_DATA_IN_BACKGROUND for a read in the background. On Android, interval reads and step totals report it without READ permission. On iOS, it also reports a read of a type that the app never requested.No
invalidArgumentINVALID_ARGUMENTThe request is not valid, for example a preferred unit that cannot express the data type.No
notSupportedNOT_SUPPORTEDThe data type is not available on this platform or device. On iOS, reads of a type that is newer than the running iOS version report it.No
unavailableUNAVAILABLEHealth Connect cannot be reached or is busy, for example while it syncs data.Yes
deviceLockedDEVICE_LOCKEDOn iOS, protected health data cannot be read while the device is locked.Yes
dataTooLargeDATA_TOO_LARGEThe platform cannot return this much data in one call. Use a smaller pageSize or a shorter time range.No
unknownHEALTH_ERROR and othersAny other error.No

A missing READ permission is not an error in getHealthDataFromTypes() and getHealthDataPages(): they return only the data that the app wrote itself. See Reads without the read permission.

The platform codes from before 14.0.0, which some calls still report, map to the matching value:

Platform codeMaps to
PERMISSION_ERRORpermissionDenied
ARGUMENT_ERROR, INVALID_TYPEinvalidArgument
UNSUPPORTED_FEATUREnotSupported
STEPS_ERROR, STATISTICS_ERROR, ROUTE_ERROR and any other codeunknown

Codes may be added in minor releases, so give a switch over HealthErrorCode a default case.

Retryable errors

The plugin never retries on its own. isRetryable is true for these three codes:

CodeCauseWhen to retry
rateLimitExceededThe app used up a Health Connect API quota. Most writes then return false instead of throwing.Later. Quotas refill continuously and vary with the Health Connect version; see Health Connect limits.
unavailableHealth Connect cannot be reached or is busy, for example while it syncs data.After a short wait.
deviceLockediOS protects health data while the device is locked.Once the user unlocks the device.

What to call again depends on the method:

  • getHealthDataFromTypes() fails as a whole. Read all of its types again, and do not record sync progress for any of them.
  • getHealthDataPages() ends the stream with the error, and the pages already delivered stay valid. Read the unfinished time window again; see Data pages.
  • After a getChanges() error, call it again later with the same token.

Plain platform exceptions

Writes, deletes and permission methods throw a plain PlatformException when the platform reports an error, not a HealthPlatformException. HealthErrorCode.fromPlatformCode() turns its code into a HealthErrorCode, including the codes from before 14.0.0:

try {
  await health.writeHealthData(
    value: 70.5, // kg
    type: HealthDataType.WEIGHT,
    startTime: time,
  );
} on PlatformException catch (e) {
  final code = HealthErrorCode.fromPlatformCode(e.code);
  if (code == HealthErrorCode.invalidArgument) {
    // The platform rejected the value
  }
}

Failures by method

MethodOn failure
getHealthDataFromTypes()Throws HealthPlatformException. An empty list means only that there is no data the app may read.
getHealthDataPages()The stream emits the HealthPlatformException or HealthException and closes. The pages already delivered stay valid.
getHealthIntervalDataFromTypes()Throws HealthPlatformException, for example with permissionDenied on Android without READ permission for the type. On iOS, a type without intervals, such as WORKOUT, throws one with invalidArgument.
getHealthDataByUUID()Returns null when the record is not found or, without READ permission, belongs to another app. Throws HealthPlatformException on other failures, on Android with permissionDenied when the app has neither READ nor WRITE permission.
getTotalStepsInInterval()Throws HealthPlatformException, for example with permissionDenied on Android without READ permission for steps. Returns 0 when there are no steps.
getChangesToken(), getChanges()Throw HealthPlatformException, and return null only on iOS. getChanges() returns changesTokenExpired: true when Health Connect cannot return the pending changes because they are too many. It does the same when one change holds more than 100,000 data points. Then create a new token and read the data again; see Change tracking.
getHealthAggregateDataFromTypes()Deprecated: throws an UnsupportedError without calling the platform. See Replace aggregate reads.
writeSleepSession()Throws an ArgumentError before anything is written when startTime is not before endTime or a stage is not valid. On iOS, it also throws one when recordingMethod is not manual or automatic. Returns false when the platform does not save the session. On iOS, throws a PlatformException with code INVALID_ARGUMENT for a session that HealthKit does not accept, such as one longer than 4 days.
writeMindfulnessSession()Throws an ArgumentError before anything is written when startTime is not before endTime or, on iOS, recordingMethod is not manual or automatic. Throws a HealthException with notSupported where Health Connect has no mindfulness sessions. Returns false when the platform does not save the session. On iOS, throws a PlatformException with code INVALID_ARGUMENT for a session that HealthKit does not accept, such as one longer than 28 days.
writeWorkoutData(), writeWorkoutDataUUID()Throw an ArgumentError before anything is written for a client record ID or sync identifier without its version, or a version without its ID. They also throw one for a zone offset of more than 18 hours or swimming details that are not valid. On iOS, a recordingMethod other than manual or automatic also throws one. Throw a HealthException with notSupported for a workout type that the platform does not have. Return false, or an empty string, when the platform does not save the workout. On iOS, throw a PlatformException with code INVALID_ARGUMENT for a workout that HealthKit does not accept.
getRequestStatusForAuthorization()Throws a PlatformException when HealthKit cannot determine the status, and an ArgumentError for WRITE or READ_WRITE access to a read-only type. Returns null on Android.

Most other writes, deletes and permission methods, and the Health Connect checks, return false on failure, or an empty string where they return a UUID. These calls fail differently:

  • On Android, writeHealthData() and writeHealthDataUUID() throw a PlatformException with code INVALID_ARGUMENT when endTime equals startTime for a type with a duration, such as STEPS.
  • On iOS, writeHealthData() and writeHealthDataUUID() throw an ArgumentError for a read-only type.
  • On iOS, writing data that HealthKit does not accept, such as a sample longer than its type allows, throws a PlatformException with code INVALID_ARGUMENT.
  • On Android, hasPermissions() throws a PlatformException when Health Connect fails.
  • On Android, a permission request made while the Health Connect permission dialog is open returns false at once.
  • On Android, deleteByUUID() without type throws a PlatformException with code error.
  • On iOS, deleteByClientRecordId() throws a MissingPluginException: iOS has no client record IDs.

On Android, reads check preferredUnits before anything is read. A unit that Health Connect values are not converted to throws a HealthException with invalidArgument. Besides each type's default unit, the values are converted only to these units:

TypeOther units
WEIGHTPOUND
HEIGHTCENTIMETER, INCH
BODY_TEMPERATURE, SKIN_TEMPERATUREDEGREE_FAHRENHEIT, KELVIN
BLOOD_GLUCOSEMILLIMOLES_PER_LITER

See also

Upgrading from 13.x

Update a 13.x app for the breaking changes in 14.0.0.

Health Connect limits

API quotas, the calls each read costs and how to stay within them.

Data pages

Read large time ranges page by page with bounded memory.

Permissions

Request, check and revoke access to health data.

Quick links

Page · DocumentationCARP DocumentationPage · DocumentationIntroductionPage · DocumentationQuickstartPage · DocumentationTerminologyPage · DocumentationArchitecture