From 5f65a84b022446ac66a8ba8c0c60d5d749a3bafa Mon Sep 17 00:00:00 2001 From: FinnHornhoover <30576665+FinnHornhoover@users.noreply.github.com> Date: Sat, 22 Aug 2020 09:46:52 +0300 Subject: [PATCH] Fix unhandled exception in NPCManager (#24) * fixed PROTOCOL_VERSION not being defined * handle exceptions in NPCManager init --- src/NPCManager.cpp | 39 ++++++++++++++------------------------- 1 file changed, 14 insertions(+), 25 deletions(-) diff --git a/src/NPCManager.cpp b/src/NPCManager.cpp index 42206dd..52cc07e 100644 --- a/src/NPCManager.cpp +++ b/src/NPCManager.cpp @@ -10,37 +10,26 @@ std::map NPCManager::NPCs; -#define CHECKNPC(x) if (NPC.value().find(x) == NPC.value().end()) { \ - std::cout << "[WARN] Malformed NPC.json file! failed to find " << x << std::endl; \ - return; \ - } - void NPCManager::init() { // load NPCs from NPCs.json into our NPC manager - std::ifstream inFile("NPCs.json"); - nlohmann::json jsonData; + try { + std::ifstream inFile("NPCs.json"); + nlohmann::json jsonData; - // read file into jsonData - inFile >> jsonData; + // read file into jsonData + inFile >> jsonData; - for (auto& NPC : jsonData.items()) { - std::string name = NPC.key(); + for (auto& npc : jsonData) { + BaseNPC tmp(npc["x"], npc["y"], npc["z"], npc["id"]); + NPCManager::NPCs[tmp.appearanceData.iNPC_ID] = tmp; + } - // sanity checks - CHECKNPC("id") - CHECKNPC("x") - CHECKNPC("y") - CHECKNPC("z") - - int x = (int)(jsonData[NPC.key()]["x"]); - int y = (int)(jsonData[NPC.key()]["y"]); - int z = (int)(jsonData[NPC.key()]["z"]); - BaseNPC tmp(x, y, z, jsonData[NPC.key()]["id"]); - NPCManager::NPCs[tmp.appearanceData.iNPC_ID] = tmp; + std::cout << "populated " << NPCs.size() << " NPCs" << std::endl; + } + catch (const std::exception& err) { + std::cerr << "[WARN] Malformed NPC.json file! Reason:" << std::endl << err.what() << std::endl; } - - std::cout << "populated " << NPCs.size() << " NPCs" << std::endl; } #undef CHECKNPC @@ -49,7 +38,7 @@ void NPCManager::updatePlayerNPCS(CNSocket* sock, PlayerView& view) { std::list yesView; std::list noView; - for (auto pair : NPCs) { + for (auto& pair : NPCs) { int diffX = abs(view.plr.x - pair.second.appearanceData.iX); int diffY = abs(view.plr.y - pair.second.appearanceData.iY);