Skip to content

Instantly share code, notes, and snippets.

@apivovarov
Created January 10, 2025 01:51
Show Gist options
  • Save apivovarov/78bde66c5941ddef87f297ab6fd3bec9 to your computer and use it in GitHub Desktop.
Save apivovarov/78bde66c5941ddef87f297ab6fd3bec9 to your computer and use it in GitHub Desktop.
#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