Created
January 10, 2025 01:51
-
-
Save apivovarov/78bde66c5941ddef87f297ab6fd3bec9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <exception> | |
#include <string> | |
#include <sstream> | |
#include <execinfo.h> | |
#include <cxxabi.h> | |
#include <vector> | |
class ExceptionWithStackTrace : public std::exception { | |
public: | |
explicit ExceptionWithStackTrace(const std::string& message) | |
: message_(message), stackTrace_(captureStackTrace()) {} | |
const char* what() const noexcept override { | |
return message_.c_str(); | |
} | |
const std::string& stackTrace() const { | |
return stackTrace_; | |
} | |
private: | |
std::string message_; | |
std::string stackTrace_; | |
static std::string captureStackTrace() { | |
constexpr int maxFrames = 64; | |
void* frames[maxFrames]; | |
int numFrames = backtrace(frames, maxFrames); | |
char** symbols = backtrace_symbols(frames, numFrames); | |
std::ostringstream stack; | |
for (int i = 0; i < numFrames; ++i) { | |
stack << symbols[i] << '\n'; | |
} | |
free(symbols); | |
return stack.str(); | |
} | |
}; | |
int main() { | |
try { | |
throw ExceptionWithStackTrace("An error occurred!"); | |
} catch (const ExceptionWithStackTrace& ex) { | |
std::cerr << "Error: " << ex.what() << "\nStack trace:\n" << ex.stackTrace(); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment