Handle subscribe exceptions

This commit is contained in:
2025-12-29 21:01:19 +01:00
parent fffc2adfc2
commit 0f3d0c60b6
2 changed files with 14 additions and 10 deletions

View File

@@ -8,8 +8,8 @@ public class Logger {
} }
public static void displayError(String message){ public static void displayError(String message){
String GREEN = "\u001B[32m"; final String RED = "\u001B[31m";
String RESET = "\u001B[0m"; final String RESET = "\u001B[0m";
System.out.println(GREEN + "[Error] --- " + message + RESET); System.out.println(RED + "[Error] --- " + message + RESET);
} }
} }

View File

@@ -65,7 +65,7 @@ public class MqttService {
connect(subscriber, options); connect(subscriber, options);
subscriber.subscribe(topic, 1); subscriber.subscribe(topic, 1);
} catch (MqttException e) { } catch (Exception e) {
Logger.displayError("An error occurred while subscribing : " + e.getMessage()); Logger.displayError("An error occurred while subscribing : " + e.getMessage());
} }
} }
@@ -101,12 +101,16 @@ public class MqttService {
} }
private void connect(MqttClient client, MqttConnectOptions options) throws MqttException { private void connect(MqttClient client, MqttConnectOptions options) throws MqttException {
if (client.isConnected()) return; try {
if (options == null) { if (client.isConnected()) return;
client.connect(); if (options == null) {
} else { client.connect();
client.connect(options); } else {
client.connect(options);
}
Logger.displayInfo("Connected to " + client.getCurrentServerURI());
} catch (Exception e){
Logger.displayError("Unable to connect to broker : " + e.getMessage());
} }
Logger.displayInfo("Connected to " + client.getCurrentServerURI());
} }
} }