From f4c3367e433dad570fe4e499d4342fea63c0a65f Mon Sep 17 00:00:00 2001
From: Ivan Savenko <saven.ivan@gmail.com>
Date: Tue, 28 Jan 2025 20:21:33 +0000
Subject: [PATCH] Workarounds for crashes from Google Play

- Do not crash on failure to read json from disk
- Add more debug information for crash on BattleHex access
---
 client/renderSDL/RenderHandler.cpp | 18 +++++++++++++-----
 lib/battle/BattleHex.h             |  2 +-
 2 files changed, 14 insertions(+), 6 deletions(-)

diff --git a/client/renderSDL/RenderHandler.cpp b/client/renderSDL/RenderHandler.cpp
index 08dbf37da..5a6230d95 100644
--- a/client/renderSDL/RenderHandler.cpp
+++ b/client/renderSDL/RenderHandler.cpp
@@ -25,6 +25,7 @@
 
 #include "../../lib/CConfigHandler.h"
 #include "../../lib/CThreadHelper.h"
+#include "../../lib/ExceptionsCommon.h"
 #include "../../lib/VCMIDirs.h"
 #include "../../lib/constants/StringConstants.h"
 #include "../../lib/entities/building/CBuilding.h"
@@ -146,13 +147,20 @@ RenderHandler::AnimationLayoutMap & RenderHandler::getAnimationLayout(const Anim
 
 	for(auto & loader : configList)
 	{
-		auto stream = loader->load(jsonResource);
-		std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
-		stream->read(textData.get(), stream->getSize());
+		try {
+			auto stream = loader->load(jsonResource);
+			std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
+			stream->read(textData.get(), stream->getSize());
 
-		const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), path.getOriginalName());
+			const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), path.getOriginalName());
 
-		initFromJson(result, config, mode);
+			initFromJson(result, config, mode);
+		}
+		catch (const DataLoadingException & e)
+		{
+			// FIXME: sometimes triggered by generated animation assets, e.g. lava/water tiles
+			logGlobal->error("Failed to load animation file! Reason: %s", e.what());
+		}
 	}
 
 	animationLayouts[actualPath] = result;
diff --git a/lib/battle/BattleHex.h b/lib/battle/BattleHex.h
index 34657bbab..d13fa534c 100644
--- a/lib/battle/BattleHex.h
+++ b/lib/battle/BattleHex.h
@@ -118,7 +118,7 @@ public:
 		if(hasToBeValid)
 		{
 			if(x < 0 || x >= GameConstants::BFIELD_WIDTH || y < 0 || y >= GameConstants::BFIELD_HEIGHT)
-				throw std::runtime_error("Valid hex required");
+				throw std::runtime_error("Hex at (" + std::to_string(x) + ", " + std::to_string(y) + ") is not valid!");
 		}
 
 		hex = x + y * GameConstants::BFIELD_WIDTH;