From 1dee4cd4a894905e458af7de0dcdbadeca2539c0 Mon Sep 17 00:00:00 2001 From: Deukhoofd Date: Sat, 15 Aug 2020 13:59:10 +0200 Subject: [PATCH] Better handling for Exception stack trace testing. --- src/Exception.hpp | 23 +++++++++++++++++------ tests/ExceptionTests.cpp | 5 +++++ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/Exception.hpp b/src/Exception.hpp index 814aa63..cc9428f 100644 --- a/src/Exception.hpp +++ b/src/Exception.hpp @@ -18,26 +18,37 @@ namespace ArbUt { [[nodiscard]] const char* what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_NOTHROW override { return _msg.c_str(); } - [[nodiscard]] std::string GetStacktrace(size_t depth = 6) const { + [[nodiscard]] std::string GetStacktrace(size_t depth = 6, bool include_addr = true) const { backward::TraceResolver tr; tr.load_stacktrace(_stack); std::stringstream ss; for (size_t i = 3; i < _stack.size() && i < depth + 3; ++i) { backward::ResolvedTrace trace = tr.resolve(_stack[i]); - if (trace.source.filename.empty()){ + if (trace.source.filename.empty()) { + auto objectName = + (strrchr(trace.object_filename.c_str(), '/') ? strrchr(trace.object_filename.c_str(), '/') + 1 + : trace.object_filename.c_str()); + auto function = trace.object_function; + if (function.length() > 70) { + function = function.substr(0, 67); + function += "..."; + } + ss << objectName; + if (include_addr){ + ss << "[" << trace.addr << "]"; + } + ss << " " << function << std::endl; - } - else{ + } else { auto fileName = (strrchr(trace.source.filename.c_str(), '/') ? strrchr(trace.source.filename.c_str(), '/') + 1 : trace.source.filename.c_str()); auto function = trace.object_function; - if (function.length() > 70){ + if (function.length() > 70) { function = function.substr(0, 67); function += "..."; } ss << fileName << "[" << trace.source.line << "] " << function << std::endl; - } } return ss.str(); diff --git a/tests/ExceptionTests.cpp b/tests/ExceptionTests.cpp index f9d6459..9e723e8 100644 --- a/tests/ExceptionTests.cpp +++ b/tests/ExceptionTests.cpp @@ -8,8 +8,13 @@ TEST_CASE("Throw exception, get stack trace") { throw ArbUt::Exception("foobar"); } catch (const ArbUt::Exception& e) { +#ifndef NDEBUG REQUIRE(e.GetStacktrace(1) == "ExceptionTests.cpp[8] ____C_A_T_C_H____T_E_S_T____0()\n"); +#else + REQUIRE(e.GetStacktrace(1, false) == + "ArbutilsTests Catch::RunContext::runTest(Catch::TestCase const&)\n"); +#endif } }