Skip to main content

Error Handling

All async APIs in the SDK return error information via NSError. This guide covers the error structure, complete error codes, and best practices.

Error Structure

Every NSError returned by the SDK contains:

FieldDescription
domainError domain in the format TS[Module]ErrorDomain, e.g. TSBleErrorDomain
codeNumeric error code (see categories below)
userInfo[NSLocalizedDescriptionKey]Human-readable error description
userInfo[NSUnderlyingErrorKey]Underlying system error, if any

Callback Conventions

The SDK uses two callback patterns:

1. TSCompletionBlock (success/failure)

typedef void(^TSCompletionBlock)(BOOL isSuccess, NSError * _Nullable error);
[[TopStepComKit sharedInstance].bleConnector disconnectCompletion:^(BOOL isSuccess, NSError *error) {
if (isSuccess) {
// Operation succeeded
} else {
[self handleError:error];
}
}];

2. Data Callback (error-only check)

[[TopStepComKit sharedInstance].heartRate getHistoryDataFrom:startDate to:endDate
completion:^(NSArray *records, NSError *error) {
if (error) {
[self handleError:error];
return;
}
// Process records normally
}];

General Error Codes (TSErrorCode)

Applies to all modules. Defined in TSErrorEnum.h.

System Errors (1001–1004)

EnumCodeMeaning
eTSErrorUnknown1001Unknown error
eTSErrorSDKInitFailed1002SDK initialization failed
eTSErrorLicenseIncorrect1003SDK license error
eTSErrorSDKConfigError1004SDK configuration error

Device Status Errors (2001–2006)

EnumCodeMeaningSuggested Action
eTSErrorNotReady2001Device not readyWait for connection to complete, then retry
eTSErrorLowBattery2002Battery too low (< 30%)Prompt user to charge the device
eTSErrorUnConnected2003Device not connectedPrompt user to reconnect
eTSErrorNotSupport2004Feature not supportedHide the corresponding UI entry
eTSErrorNoSpace2005Device storage fullPrompt user to free up device space
eTSErrorIsBusy2006Device is busyRetry after a short delay

Parameter Errors (3001–3004)

EnumCodeMeaning
eTSErrorInvalidParam3001Parameter does not exist
eTSErrorParamError3002Parameter error
eTSErrorInvalidTypeError3003Invalid parameter type
eTSErrorParamSizeError3004Invalid parameter size

Data Operation Errors (4001–4004)

EnumCodeMeaning
eTSErrorDataGetFailed4001Data retrieval failed
eTSErrorDataSetFailed4002Data setting failed
eTSErrorDataFormatError4003Data format error
eTSErrorDataIsEmpty4004Data is empty

Task Errors (5001–5003)

EnumCodeMeaningSuggested Action
eTSErrorPreTaskExecuting5001Task in progress (e.g. OTA)Wait for completion before retrying
eTSErrorTaskExecutionFailed5002Task execution failedPrompt user to retry
eTSErrorTaskNotStarted5003Task not startedCheck call sequence

Communication Errors (6001–6008)

EnumCodeMeaningSuggested Action
eTSErrorTimeoutError6001Communication timeoutRetry the operation
eTSErrorTransmissionInterrupted6002Data transmission interruptedCheck device proximity, retry
eTSErrorSignalInterference6003Signal interference or lossReduce interference sources, retry
eTSErrorPacketLoss6004Packet lossRetry the operation
eTSErrorProtocolMismatch6005Protocol mismatchUpgrade SDK or firmware
eTSErrorConnectionReset6006Connection reset by peerReconnect the device
eTSErrorBufferOverflow6007Buffer overflowReduce send frequency
eTSErrorChannelBusy6008Channel busyRetry after a short delay

User Operation Errors (7001)

EnumCodeMeaning
eTSErrorUserCancelled7001User cancelled operation

Bluetooth Connection Error Codes (TSBleConnectionError)

Bluetooth-specific errors defined in TSErrorEnum.h, accessible via error.code.

Parameter Errors (9001–9004)

EnumCodeMeaning
eTSBleErrorInvalidRandomCode9001Invalid QR code parameter
eTSBleErrorInvalidUserId9002Invalid user ID parameter
eTSBleErrorInvalidParam9003Invalid parameter
eTSBleErrorInvalidHandle9004Invalid handle

General Errors (9101–9106)

EnumCodeMeaningSuggested Action
eTSBleErrorUnknown9101Unknown errorPrompt user to retry
eTSBleErrorTimeout9102Connection timeoutCheck if device is in range; retry
eTSBleErrorDisconnected9103Connection unexpectedly droppedPrompt user to reconnect
eTSBleErrorOutOfSpace9104Out of storage spacePrompt user to free up device space
eTSBleErrorUUIDNotAllowed9105UUID not allowedCheck device compatibility
eTSBleErrorAlreadyAdvertising9106Already advertisingWait for advertising to finish

Permission & System Errors (9201–9206)

EnumCodeMeaningSuggested Action
eTSBleErrorBluetoothOff9201Bluetooth is offPrompt user to turn on system Bluetooth
eTSBleErrorBluetoothUnsupported9202Bluetooth not supportedInform user device doesn't support BLE
eTSBleErrorPermissionDenied9203Bluetooth permission deniedGuide user to Settings → Privacy → Bluetooth
eTSBleErrorSystemServiceUnavailable9204System BT service unavailablePrompt user to restart phone
eTSBleErrorBluetoothStateUnknown9205Bluetooth state unknownWait for BT ready, then retry
eTSBleErrorBluetoothResetting9206Bluetooth is resettingWait for reset to complete, then retry

Connection Process Errors (9301–9308)

EnumCodeMeaningSuggested Action
eTSBleErrorConnectionFailed9301General connection failureRetry connection
eTSBleErrorGattConnectFailed9302GATT connection failedRestart Bluetooth and retry
eTSBleErrorDeviceOutOfRange9303Device out of rangeMove closer to device and retry
eTSBleErrorWeakSignal9304Signal too weakMove closer to device and retry
eTSBleErrorSignalLost9305Signal lostMove closer to device and retry
eTSBleErrorConnectionLimitReached9306Connection limit reachedDisconnect other devices first
eTSBleErrorUnknownDevice9307Unknown deviceRe-scan and re-select device
eTSBleErrorOperationNotSupported9308Operation not supportedCheck device firmware version

Authentication Errors (9404–9413, 9499)

EnumCodeMeaningSuggested Action
eTSBleErrorEncryptionFailed9404Encryption failedRe-bind the device
eTSBleErrorPeerRemovedPairingInfo9405Pairing info removed by peerRe-bind the device
eTSBleErrorEncryptionTimeout9406Encryption timed outRetry connection
eTSBleErrorUserIdMismatch9407User ID mismatchCheck the userId parameter
eTSBleErrorBindCancelledByUser9408Binding cancelled by userGuide user to retry
eTSBleErrorBindTimeout9409Binding timed outReinitiate binding
eTSBleErrorClassicBluetoothNotConnected9410Classic BT not connectedCheck classic Bluetooth state
eTSBleErrorLowBatteryCannotDeleteData9411Battery too low to delete dataPrompt user to charge device
eTSBleErrorDeviceFactoryResetting9412Device factory resettingWait for reset to complete
eTSBleErrorFactoryResetRequired9413Factory reset required to re-bindAsk user to factory reset the device
eTSBleErrorAuthenticationUnknown9499Auth failed (unknown reason)Retry connection

Device State Errors (9501–9506)

EnumCodeMeaningSuggested Action
eTSBleErrorConnectedByOthers9501Device connected by another hostAsk user to disconnect from other phone
eTSBleErrorDeviceAlreadyBound9502Device already boundAsk user to unbind first
eTSBleErrorLowBattery9503Device battery too lowPrompt user to charge device
eTSBleErrorDFUMode9504Device in DFU modeWait for DFU to finish or restart device
eTSBleErrorDeviceSleeping9505Device is sleepingWake device and retry
eTSBleErrorTooManyPairedDevices9506Too many paired devicesRemove some paired records

Service & Protocol Errors (9601–9605)

EnumCodeMeaningSuggested Action
eTSBleErrorPeripheralNotFound9601Peripheral not foundRe-scan for devices
eTSBleErrorServiceNotFound9602Required service not foundCheck device firmware version
eTSBleErrorCharacteristicNotFound9603Characteristic not foundCheck device firmware version
eTSBleErrorProtocolVersionMismatch9604Protocol version mismatchUpgrade SDK or firmware
eTSBleErrorMtuNegotiationFailed9605MTU negotiation failedRetry connection

User Actions (9701–9702)

EnumCodeMeaning
eTSBleErrorDisconnectedByUser9701Disconnected by user
eTSBleErrorCancelledByUser9702Connection cancelled by user

Scan Completion Reasons (TSScanCompletionReason)

Enum ValueDescriptionSuggested Action
eTSScanCompleteReasonTimeoutScan timed outInform user no device found; offer retry
eTSScanCompleteReasonBleNotReadyBluetooth not readyWait for BT initialization and retry
eTSScanCompleteReasonPermissionDeniedPermission deniedGuide user to enable Bluetooth in Settings
eTSScanCompleteReasonUserStoppedUser stopped scanNormal termination; no action needed
eTSScanCompleteReasonSystemErrorSystem errorRestart Bluetooth and retry

Feature Support Check

Always call isSupport before invoking a feature interface:

id<TSHeartRateInterface> heartRate = [TopStepComKit sharedInstance].heartRate;

if (![heartRate isSupport]) {
TSLog(@"Heart rate not supported on this device");
return;
}

[heartRate startMeasureWithParam:nil ...];

Unified Error Handler

Centralizing error handling reduces boilerplate:

- (void)handleSDKError:(NSError *)error context:(NSString *)context {
if (!error) return;

TSLog(@"[%@] domain=%@ code=%ld: %@",
context,
error.domain,
(long)error.code,
error.localizedDescription);

switch (error.code) {
// Permission / BT state → guide user
case eTSBleErrorPermissionDenied:
case eTSBleErrorBluetoothOff:
[self showBluetoothSettingsAlert];
break;

// Timeout / signal → retryable
case eTSBleErrorTimeout:
case eTSBleErrorSignalLost:
case eTSErrorTimeoutError:
[self retryWithDelay];
break;

// Busy → retry later
case eTSErrorIsBusy:
case eTSBleErrorChannelBusy:
[self scheduleRetry];
break;

// Not supported → hide UI
case eTSErrorNotSupport:
[self hideUnsupportedFeature:context];
break;

default:
[self showErrorAlert:error.localizedDescription];
break;
}
}

Bluetooth Permission Alert

- (void)showBluetoothSettingsAlert {
UIAlertController *alert = [UIAlertController
alertControllerWithTitle:@"Bluetooth Access Required"
message:@"Please go to Settings → Privacy → Bluetooth to enable access."
preferredStyle:UIAlertControllerStyleAlert];

[alert addAction:[UIAlertAction actionWithTitle:@"Open Settings"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
}]];

[alert addAction:[UIAlertAction actionWithTitle:@"Cancel"
style:UIAlertActionStyleCancel
handler:nil]];

[self presentViewController:alert animated:YES completion:nil];
}

Important Notes

  1. Never ignore the error parameter — always check error before assuming success, even when isSuccess = YES
  2. UI updates on the main thread — all SDK callbacks execute on the main thread; you can update UI directly
  3. Recoverable vs. non-recoverable errors — timeout errors can be retried; permission errors require user action; unsupported-feature errors should hide the corresponding UI entry
  4. Log and report errors — send error.domain and error.code to your backend for diagnostics