From d013496f3fdfce682202fb7355af185d749e8825 Mon Sep 17 00:00:00 2001 From: Avineet Singh Date: Sat, 18 Oct 2025 23:02:33 +0530 Subject: [PATCH] fix: add error handling for WiFi.scanNetworks() in /scan endpoint - Check for negative return values from WiFi.scanNetworks() - Return 500 error with JSON error response when scan fails - Add WiFi.scanDelete() to prevent memory leak - Improve serial output to indicate scan success/failure - Fixes issue where scan errors were masked by empty array response Fixes potential crashes and improves debugging experience when WiFi scan operations fail due to hardware issues or interference. --- src/EasyWiFi.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/EasyWiFi.cpp b/src/EasyWiFi.cpp index 2d8fee9..6c8fa6d 100644 --- a/src/EasyWiFi.cpp +++ b/src/EasyWiFi.cpp @@ -298,8 +298,17 @@ void EasyWiFi::startPortal() { }); server.on("/scan", [this]() { - int networks = WiFi.scanNetworks(); - Serial.printf("Scan complete: %d", networks); + int networks = WiFi.scanNetworks(); + + // Check for scan errors + if (networks < 0) { + Serial.printf("WiFi scan failed with error code: %d\n", networks); + server.send(500, "application/json", + "{\"error\":\"WiFi scan failed\",\"code\":" + String(networks) + "}"); + return; + } + + Serial.printf("Scan complete: %d networks found\n", networks); String json = "["; for (int i = 0; i < networks; i++) { @@ -312,6 +321,7 @@ void EasyWiFi::startPortal() { } json += "]"; + WiFi.scanDelete(); // Clean up scan results from memory server.send(200, "application/json", json); });