SimpleBLE

Error Handling

How SimpleBLE reports errors in each language, which errors are recoverable, what timeouts mean, and what happens to in-flight operations on disconnect.

SimpleBLE classifies every failure as one of the errors below. The C++ library throws them as exceptions, and every binding reports the same classification in its own idiom, as described in Errors in each language.

Exception taxonomy

ExceptionError codeThrown whenTypical cause
NotInitializedOBJECT_NOT_INITIALIZEDAny method is called on a default-constructed Adapter, Peripheral, or SimpleBLE::Local::* objectProgramming error — obtain objects from get_adapters(), scan results, or create_local_peripheral()
InvalidReferenceINVALID_BACKEND_REFERENCEThe internal object behind a handle is no longer validProgramming error — a stale handle outlived its backend object
NotConnectedPERIPHERAL_NOT_CONNECTEDA GATT operation is called while the peripheral is not connectedDevice disconnected, or connect() was never called
ServiceNotFoundGATT_SERVICE_NOT_FOUNDThe requested service UUID isn't in the discovered GATT databaseWrong UUID, or the device doesn't expose that service
CharacteristicNotFoundGATT_CHARACTERISTIC_NOT_FOUNDThe requested characteristic UUID isn't under that serviceWrong UUID pair
DescriptorNotFoundGATT_DESCRIPTOR_NOT_FOUNDThe requested descriptor UUID isn't under that characteristicWrong UUID triple
OperationNotSupportedOPERATION_NOT_SUPPORTEDThe characteristic doesn't have the required capability, or the backend doesn't support the operatione.g. calling read() on a write-only characteristic
OperationFailedOPERATION_FAILEDThe operation was attempted but did not complete successfullyTimeouts, stack-level errors, connection failures, mutating a local peripheral while it is started
WinRTExceptionWINRT_EXCEPTIONA WinRT API call failed (Windows only)Carries the WinRT error code and message
WinRTAccessDeniedWINRT_ACCESS_DENIEDA WinRT API call was denied access (Windows only)A WinRTException whose WinRT error code is E_ACCESSDENIED
CoreBluetoothExceptionCORE_BLUETOOTH_EXCEPTIONA CoreBluetooth operation failed (macOS/iOS only)Carries the NSError description
InvalidArgumentINVALID_ARGUMENTAn argument is out of rangeProgramming error, such as a negative scan_for() duration
AdapterInUseADAPTER_IN_USEAnother process holds the adapterA Dongl whose serial port another program has open. Such a Dongl is still listed, and its first operation raises this error
Any other std::exceptionUNCLASSIFIED_EXCEPTIONA lower layer failed without a SimpleBLE classificationSee Unclassified errors

The error codes are the values of SimpleBLE::ErrorCode. The bindings spell them in their own style, such as SIMPLEBLE_ERROR_PERIPHERAL_NOT_CONNECTED in C and PeripheralNotConnected in C#, Go, and Rust.

Recoverable vs. fatal

As a rule of thumb:

  • Programming errors — fix your code, don't retry: NotInitialized, InvalidReference, InvalidArgument, OperationNotSupported, and the three *NotFound exceptions. If the UUIDs and capabilities are right, these should never fire in production. The one nuance: *NotFound can also occur when talking to a fleet of devices with different firmware revisions — in that case treat it as "this device doesn't support the feature," not as a retry candidate.
  • Runtime errors — retry or reconnect: NotConnected, OperationFailed, WinRTException, CoreBluetoothException, and unclassified errors. These reflect transient radio and stack conditions. The standard recovery is: check is_connected(), reconnect if needed, re-establish subscriptions, and retry the operation. See the reconnect loop recipe for a production-ready pattern.

Unclassified errors

Platform-layer exceptions

On Android, GATT operation timeouts surface through the public API as a plain std::runtime_error, without being translated into a SimpleBLE::Exception type.

These errors carry the lower layer's message and no classification. C++ code sees them as a std::exception that isn't a BaseException, and every binding reports them as unclassified, as shown below for each language.

Errors in each language

All library-defined exceptions live in the SimpleBLE::Exception namespace (declared in simpleble/Exceptions.h) and derive from SimpleBLE::Exception::BaseException, which itself derives from std::runtime_error. To cover both the classified exceptions and unclassified errors, catch at two levels:

try {
    auto value = peripheral.read(service_uuid, characteristic_uuid);
} catch (const SimpleBLE::Exception::NotConnected& e) {
    // Reconnect and retry.
} catch (const SimpleBLE::Exception::BaseException& e) {
    // Classified SimpleBLE error: inspect the concrete type if needed.
    std::cerr << "BLE error: " << e.what() << std::endl;
} catch (const std::exception& e) {
    // Lower-layer error that escaped translation (DBus failure, timeout, ...).
    std::cerr << "Unclassified error: " << e.what() << std::endl;
}

Fallible calls take a required simpleble_error_t** slot and fill it with an owned error object when they fail. simpleble_error_code() returns its code, such as SIMPLEBLE_ERROR_PERIPHERAL_NOT_CONNECTED, and simpleble_error_message() its message. Unclassified errors have the code SIMPLEBLE_ERROR_UNCLASSIFIED_EXCEPTION. Inspect the slot before reusing it, and release it with simpleble_error_release(); see the C migration guide.

simpleble_error_t* error = NULL;
size_t length = 0;
uint8_t* data = simpleble_peripheral_read(peripheral, service, characteristic, &length, &error);
if (error && simpleble_error_code(error) == SIMPLEBLE_ERROR_PERIPHERAL_NOT_CONNECTED) {
    // Reconnect and retry.
} else if (error) {
    fprintf(stderr, "BLE error: %s\n", simpleble_error_message(error));
}
simpleble_free(data);
simpleble_error_release(&error);

Native failures throw BleException. Its Code property is a BleErrorCode, such as PeripheralNotConnected, and its message carries the native details. Unclassified errors have the code UnclassifiedException. Invalid arguments throw the usual ArgumentException types before reaching native code, platform-specific APIs called on another platform throw PlatformNotSupportedException, and calls on a disposed object throw ObjectDisposedException.

try
{
    byte[] value = peripheral.Read(serviceUuid, characteristicUuid);
}
catch (BleException error) when (error.Code == BleErrorCode.PeripheralNotConnected)
{
    // Reconnect and retry.
}

A failed call raises simplepyble.SimpleBLEError, a subclass of RuntimeError, or one of its subclasses named after the exception, such as NotConnectedError, with the same message text. Each error carries its simplepyble.ErrorCode in code, and a WinRT failure carries its HRESULT in native_code. Unclassified errors arrive as plain RuntimeError, so except RuntimeError catches both. See SimplePyBLE errors for the full list of subclasses.

try:
    value = peripheral.read(service_uuid, characteristic_uuid)
except simplepyble.NotConnectedError:
    peripheral.connect()
except RuntimeError as e:
    print(f"BLE error: {e}")

A failed call throws SimpleJavaBleException, a RuntimeException, or one of its subclasses named after the exception, such as NotConnectedException, with the same message text. Each carries its ErrorCode in getCode(), and unclassified errors throw SimpleJavaBleException itself with UNCLASSIFIED_EXCEPTION. See SimpleJavaBLE errors for the full list of subclasses.

try {
    byte[] value = peripheral.read(service, characteristic);
} catch (NotConnectedException e) {
    peripheral.connect();
} catch (SimpleJavaBleException e) {
    System.err.println(e.getCode() + ": " + e.getMessage());
}

Fallible methods return an error. Check classifications with errors.Is(err, ble.PeripheralNotConnected), and use errors.As with *ble.Error to inspect the native error Code and diagnostic Message. Unclassified errors have the code ble.UnclassifiedException. Methods on closed or zero-value wrappers return ble.ErrClosed.

value, err := peripheral.Read(serviceUUID, characteristicUUID)
var bleErr *ble.Error
switch {
case err == nil:
    log.Printf("Read: %x", value)
case errors.Is(err, ble.PeripheralNotConnected):
    // Reconnect and retry.
case errors.As(err, &bleErr):
    log.Printf("BLE error %s: %s", bleErr.Code, bleErr.Message)
}

Calls that can fail return simplersble::Error, which displays SimpleBLE's message. Its code() returns a simplersble::ErrorCode, such as ErrorCode::PeripheralNotConnected. Unclassified errors have the code ErrorCode::UnclassifiedException.

use simplersble::ErrorCode;

match peripheral.read(&service_uuid, &characteristic_uuid) {
    Ok(value) => println!("Read: {:?}", value),
    Err(e) if e.code() == ErrorCode::PeripheralNotConnected => peripheral.connect().unwrap(),
    Err(e) => println!("BLE error {:?}: {}", e.code(), e),
}

Failures reject with a SimpleBLEError. Its code is SimpleBLE's error code, such as 'PERIPHERAL_NOT_CONNECTED', and WinRT failures also carry the original HRESULT in nativeCode. Unclassified errors have the code 'UNCLASSIFIED_EXCEPTION'. Arguments of the wrong type or outside a 32-bit range are TypeErrors or RangeErrors, and those SimpleBLE rejects, such as a negative scanFor() duration, reject with 'INVALID_ARGUMENT'.

import { SimpleBLEError } from 'simplejsble';

try {
  const value = await peripheral.read(serviceUuid, characteristicUuid);
} catch (error) {
  if (!(error instanceof SimpleBLEError)) throw error;
  if (error.code === 'PERIPHERAL_NOT_CONNECTED') {
    // Reconnect and retry.
  }
}

Failures reject with a SimpleBLEError. Its code is SimpleBLE's error code, such as 'PERIPHERAL_NOT_CONNECTED'. Unclassified errors have the code 'UNCLASSIFIED_EXCEPTION'. Arguments of the wrong type or outside a 32-bit range are TypeErrors or RangeErrors, and those SimpleBLE rejects, such as a negative scanFor() duration, reject with 'INVALID_ARGUMENT'.

import { SimpleBLEError } from 'simplernble';

try {
  const value = await peripheral.read(serviceUuid, characteristicUuid);
} catch (error) {
  if (!(error instanceof SimpleBLEError)) throw error;
  if (error.code === 'PERIPHERAL_NOT_CONNECTED') {
    // Reconnect and retry.
  }
}

Failures are thrown as SimpleKtBleException. Its code is SimpleBLE's ErrorCode, such as PERIPHERAL_NOT_CONNECTED. Unclassified errors have the code UNCLASSIFIED_EXCEPTION. Functions declare it with @Throws, so Swift calls them with try.

try {
    val value = peripheral.read(serviceUuid, characteristicUuid)
} catch (e: SimpleKtBleException) {
    when (e.code) {
        ErrorCode.PERIPHERAL_NOT_CONNECTED -> peripheral.connect()
        else -> println("BLE error ${e.code}: ${e.message}")
    }
}

Failures are thrown as SimpleBLEError. Its code is SimpleBLE's error code, such as .peripheralNotConnected. Unclassified errors have the code .unclassifiedException.

do {
    let value = try await peripheral.read(service: serviceUUID, characteristic: characteristicUUID)
} catch let error as SimpleBLEError {
    switch error.code {
    case .peripheralNotConnected: try await peripheral.connect()
    default: print("BLE error \(error.code): \(error.message)")
    }
}

Failures throw a SimpleDartBleException, with one subclass per kind of failure, such as NotConnectedException or CharacteristicNotFoundException. Its code is SimpleBLE's ErrorCode, such as ErrorCode.peripheralNotConnected. Unclassified errors are thrown as SimpleDartBleException itself, with the code ErrorCode.unclassifiedException. Arguments outside what SimpleBLE takes, such as a UUID longer than 36 characters, throw an ArgumentError, and values SimpleBLE rejects, such as a negative scanFor() duration, throw an InvalidArgumentException.

try {
  final value = await peripheral.read(serviceUuid, characteristicUuid);
  print('Read: $value');
} on NotConnectedException {
  await peripheral.connect();
} on SimpleDartBleException catch (e) {
  print('BLE error ${e.code.name}: ${e.message}');
}

Failures raise an EBleError, with one subclass per kind of failure, such as EBleNotConnected or EBleCharacteristicNotFound. Its Code is SimpleBLE's error code, such as ecPeripheralNotConnected. Out-of-memory and unclassified failures raise EBleError itself, with the code ecOutOfMemory or ecUnclassifiedException. Arguments outside what SimpleBLE takes, such as a UUID longer than 36 characters, raise an EBleInvalidArgument, like the values SimpleBLE rejects. Exceptions that your event handlers raise go to TSimpleDelphiBLE.OnHandlerException when you set it.

try
  Value := Peripheral.Read(ServiceUuid, CharacteristicUuid);
except
  on EBleNotConnected do
    Peripheral.Connect;
  on E: EBleError do
    WriteLn('BLE error ', E.ClassName, ': ', E.Message);
end;

Native failures are thrown as SimpleDroidBleException, an unchecked exception that carries the native message.

try {
    val value = peripheral.read(serviceUuid, characteristicUuid)
} catch (e: SimpleDroidBleException) {
    Log.e("SimpleBLE", "BLE error: ${e.message}")
}

Timeout semantics

Every blocking SimpleBLE call eventually gives up; the complete per-platform timeout table lives in Concurrency. What a timeout means is worth spelling out:

  • A timeout is not a rollback. When connect() or a GATT operation throws after its timeout, the underlying OS operation may still be in flight and may even complete afterwards. SimpleBLE does not attempt to cancel it on every platform.
  • State is uncertain after a timeout. The only reliable move is to re-check observable state: call is_connected(), and if you were mid-transaction with the device, verify the device-side effect before repeating a non-idempotent write.
  • Timeouts usually surface as OperationFailed (connect/disconnect on most platforms), except for the Android timeouts described in Unclassified errors.

What happens to in-flight operations on disconnect

When a device drops the connection while an operation is blocked waiting for its result, behavior differs by platform:

PlatformIn-flight operation outcome on disconnect
LinuxBlueZ fails the pending DBus call and SimpleBLE throws OperationFailed. The on_disconnected callback fires after internal cleanup.
WindowsThe WinRT operation completes with a failure status and SimpleBLE throws OperationFailed.
macOS / iOSAn in-flight read() throws OperationFailed. Other pending operations are unblocked without an error being recorded: an in-flight write_request() can return as if it succeeded.
AndroidThe completion callback never arrives, so the operation stalls for its full 5-second timeout and then throws.

Design guidance

Treat any result that races a disconnect as suspect. Use set_callback_on_disconnected as the source of truth for link state, prefer idempotent device commands where the protocol allows, and validate critical reads (e.g. sequence numbers or checksums in the payload) rather than trusting that a returned buffer implies a healthy link.

Errors inside callbacks

Exceptions thrown from your C++ callbacks do not propagate into SimpleBLE: the library invokes every user callback inside a try/catch and logs the failure. A throwing callback will not crash your application, but it also won't be reported anywhere except the log — do your own error handling inside callbacks that matter.

On this page