From 1c22892eecf4790a348c1d0567cbe346f561a3b6 Mon Sep 17 00:00:00 2001 From: lisyarus Date: Sun, 6 Aug 2023 12:52:17 +0300 Subject: [PATCH] Add util::exception class that holds stacktrace information --- libs/util/CMakeLists.txt | 4 +- libs/util/include/psemek/util/exception.hpp | 46 +++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 libs/util/include/psemek/util/exception.hpp diff --git a/libs/util/CMakeLists.txt b/libs/util/CMakeLists.txt index b6ac1849..48e2868d 100644 --- a/libs/util/CMakeLists.txt +++ b/libs/util/CMakeLists.txt @@ -5,6 +5,8 @@ file(GLOB_RECURSE PSEMEK_UTIL_SOURCES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "so psemek_add_library(psemek-util ${PSEMEK_UTIL_HEADERS} ${PSEMEK_UTIL_SOURCES}) target_include_directories(psemek-util PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") -target_link_libraries(psemek-util PUBLIC ${CMAKE_THREAD_LIBS_INIT} Boost::boost) +target_link_libraries(psemek-util PUBLIC ${CMAKE_THREAD_LIBS_INIT} Boost::boost libbacktrace) +target_compile_definitions(psemek-util PUBLIC "-DBOOST_STACKTRACE_USE_BACKTRACE") psemek_glob_tests(psemek-util tests) + diff --git a/libs/util/include/psemek/util/exception.hpp b/libs/util/include/psemek/util/exception.hpp new file mode 100644 index 00000000..be53a1fb --- /dev/null +++ b/libs/util/include/psemek/util/exception.hpp @@ -0,0 +1,46 @@ +#pragma once + +#include + +#include +#include +#include + +namespace psemek::util +{ + + struct exception + : std::exception + { + exception(std::string message, boost::stacktrace::stacktrace stacktrace = {}) + : message_(std::move(message)) + , stacktrace_(std::move(stacktrace)) + {} + + char const * what() const noexcept override + { + return message_.data(); + } + + std::string const & message() const noexcept + { + return message_; + } + + boost::stacktrace::stacktrace const & stacktrace() const noexcept + { + return stacktrace_; + } + + private: + std::string message_; + boost::stacktrace::stacktrace stacktrace_; + }; + + inline std::ostream & operator << (std::ostream & os, exception const & e) + { + os << e.what() << '\n' << e.stacktrace(); + return os; + } + +}