Getting connection failed exception

I am handling the exception on addDisconnectedListener and on connection fail just logging internal log but what is exact reason for failure. I am getting this cast exception but i am not doing any casting just logging the exception

com.hivemq.client.mqtt.exceptions.ConnectionFailedException: java.lang.ClassCastException: android.os.NetworkOnMainThreadException cannot be cast to java.net.UnknownHostException

private fun handleMqttDisconnect(context: MqttClientDisconnectedContext) {
        when (context.cause) {
            is Mqtt5DisconnectException -> {
                handleDisconnectException(context)
            }

            // if the ConnAck message contained an error code (the ConnAck message is contained in the exception)
            is Mqtt5ConnAckException -> {
                handleConnectionAckException(context)
            }

            // if the connection is closed after the Connect message has been sent but before a ConnAck message has been received
            is ConnectionClosedException -> {
                if (context.source == MqttDisconnectSource.SERVER) {
                    logMqtt("WSConnMgr ::!! ConnectionClosedException !!", "e")
                    sendSNSAlert(context)
                    // setting it to false, otherwise its going in infinite loop of exception callback.
                    context.reconnector.reconnect(false)
                } else {
                    sendSNSAlert(context)
                }
            }

            // if an error occurs before the Connect message could be sent
            // if the internet is off coming to this exception
            is ConnectionFailedException -> {
                sendSNSAlert(context)

                logMqtt("WSConnMgr ::!! ConnectionFailedException !!", "e")
            }
        }

        if (context.cause.toString().contains("NOT_AUTHORIZED")) {
            forceLogoutUser(context)
        }
    }

Hi @Aashima

Thanks for being here. The HiveMQ Community is always open to new users and your curiosity is very welcome.

Thank you for sharing the details and the relevant code. Based on the exception you encountered:

com.hivemq.client.mqtt.exceptions.ConnectionFailedException: 
java.lang.ClassCastException: android.os.NetworkOnMainThreadException 
cannot be cast to java.net.UnknownHostException

the underlying cause appears to be that a network operation is being initiated on the Android main (UI) thread. Android enforces a strict policy against performing network operations on the main thread, and when such an operation occurs, it throws a NetworkOnMainThreadException.

Although your code does not include any casting, the exception arises from within the HiveMQ MQTT client library. Internally, the client may attempt to handle certain failures (such as DNS resolution issues) by casting the root cause to a more specific exception type, such as UnknownHostException. However, in this case, the actual cause is NetworkOnMainThreadException, which is unrelated and incompatible with the expected type, leading to a ClassCastException.

To resolve this, please ensure that the connect() method (or any other MQTT-related network operation) is invoked from a background thread and not directly from the main thread. If you are using Kotlin, this can be done using coroutines with an appropriate dispatcher, such as Dispatchers.IO. For example:

CoroutineScope(Dispatchers.IO).launch {
    try {
        mqttClient.connect()
    } catch (e: Exception) {
        Log.e("MQTT", "Connection failed", e)
    }
}

Alternatively, you can use a traditional Java thread if you are not using coroutines. This adjustment should prevent the NetworkOnMainThreadException and, consequently, the related ClassCastException.

I hope this helps
Best,
Dasha from The HiveMQ Team