NordicSemiconductor / Android-BLE-Library

A library that makes working with Bluetooth LE on Android a pleasure. Seriously.
BSD 3-Clause "New" or "Revised" License
1.98k stars 413 forks source link

How to Catch Exception with RequestFailedException #542

Closed jianhaozh closed 6 months ago

jianhaozh commented 7 months ago

here is my code :

        setNotificationCallback(notifyCharacteristic)
            .with { _, data ->
                val bytes = data.value!!
                val msg  = String(bytes, Charsets.UTF_8)
                onNotify(msg)
            }

        enableNotifications(notifyCharacteristic)
            .fail { device, status ->
                Log.e(TAG,"enableNotifications  error:${device.name} $status")
            }
            .invalid(invalidRequestCallback)
            .enqueue()

and sometimes get the below Exception:

no.nordicsemi.android.ble.exception.RequestFailedException: Request failed with status 133
   at no.nordicsemi.android.ble.ktx.RequestSuspendKt$suspendCancellable$2$3.onRequestFailed(RequestSuspend.kt:400)
   at no.nordicsemi.android.ble.Request.lambda$notifyFail$2(Request.java:1266)
   at no.nordicsemi.android.ble.Request.$r8$lambda$I1BgyUZ88NPGZf10e7tUAZC8w_Q(Unknown Source:0)
   at no.nordicsemi.android.ble.Request$$ExternalSyntheticLambda0.run(Unknown Source:6)
   at no.nordicsemi.android.ble.Request$1.post(Request.java:172)
   at no.nordicsemi.android.ble.Request.notifyFail(Request.java:1263)
   at no.nordicsemi.android.ble.TimeoutableRequest.notifyFail(TimeoutableRequest.java:253)
   at no.nordicsemi.android.ble.BleManagerHandler$4.onConnectionStateChange(BleManagerHandler.java:2227)
   at android.bluetooth.BluetoothGatt$1$4.run(BluetoothGatt.java:266)
   at android.os.Handler.handleCallback(Handler.java:907)
   at android.os.Handler.dispatchMessage(Handler.java:105)
   at android.os.Looper.loop(Looper.java:216)
   at android.app.ActivityThread.main(ActivityThread.java:7625)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
   Suppressed: kotlinx.coroutines.internal.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@e2d3859, Dispatchers.Default]

I have tried to add the FailCallback above,but failed, this exception leads to my app crash and exit.... how to solve it Any suggestion or comment will be greatly thankful!

philips77 commented 6 months ago

The exception is thrown from a .suspend() method, not the code given above. When you use .enqueue(), the same exception is sent to .fail(...) method, but with .suspend() it's just thrown so you need to catch it.