From b84e61f1f0fb5ca00c5af475fc87a844e6964571 Mon Sep 17 00:00:00 2001 From: fantasy-peak <82742316+fantasy-peak@users.noreply.github.com> Date: Thu, 21 Dec 2023 16:33:16 +0800 Subject: [PATCH] Add custom exception (#3) --- example/main.cpp | 2 +- include/yaml_cpp_struct.hpp | 33 ++++++++++++++++++++++++++++++--- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/example/main.cpp b/example/main.cpp index d791ef6..67683ff 100644 --- a/example/main.cpp +++ b/example/main.cpp @@ -210,7 +210,7 @@ int main(int, char** argv) { // export YCS_ENV_IPS=["Google","Runoob","Taobao"] auto [cfg, error] = yaml_cpp_struct::from_yaml_env(argv[1], "YCS_ENV_"); if (!cfg) { - spdlog::error("{}", error); + spdlog::error("error: [{}]", error); return -1; } #endif diff --git a/include/yaml_cpp_struct.hpp b/include/yaml_cpp_struct.hpp index a7ff9f2..e184024 100644 --- a/include/yaml_cpp_struct.hpp +++ b/include/yaml_cpp_struct.hpp @@ -69,6 +69,28 @@ inline nlohmann::json yaml2json(const YAML::Node& root) { namespace yaml_cpp_struct { +class Exception : public std::exception { +public: + explicit Exception(const char* what) noexcept + : m_what(what) { + } + + explicit Exception(const std::string& what) noexcept + : m_what(what) { + } + + const char* what() const noexcept override { + return m_what.c_str(); + } + +protected: + Exception() noexcept { + } + +private: + std::string m_what; +}; + template inline std::string string_format(const std::string& format, Args... args) { int size_s = std::snprintf(nullptr, 0, format.c_str(), args...) + 1; @@ -139,7 +161,7 @@ inline std::tuple, std::string> from_yaml(const std::string& st } catch (const YAML::BadFile& e) { return std::make_tuple(std::nullopt, string_format("%s not found or broken", str.c_str())); } catch (const std::exception& e) { - return std::make_tuple(std::nullopt, string_format("on parsing %s: %s", str.c_str(), e.what())); + return std::make_tuple(std::nullopt, string_format("on parsing %s -> %s", str.c_str(), e.what())); } } @@ -289,7 +311,12 @@ struct convert> { } \ } \ else \ - value = yaml_cpp_struct::node_as(node[name]); \ + try { \ + value = yaml_cpp_struct::node_as(node[name]); \ + } catch (const std::runtime_error&) { \ + auto error = yaml_cpp_struct::string_format("lost: %s", name); \ + throw yaml_cpp_struct::Exception(error); \ + } \ }); \ return true; \ } \ @@ -340,7 +367,7 @@ struct convert> { rhs = value.value(); \ else { \ auto error = yaml_cpp_struct::string_format("bad enum value: %s", enum_str.c_str()); \ - throw YAML::RepresentationException(node.Mark(), error); \ + throw yaml_cpp_struct::Exception(error); \ } \ return true; \ } \