-
Notifications
You must be signed in to change notification settings - Fork 2
Advanced Usage
FloweyTheFlower420 edited this page Jul 31, 2021
·
11 revisions
Although you can use just the stacktrace::dump_stacktrace
to print out the stacktrace, you can also use some of the more "complex" features.
Use/extend the stack_aware_exception
class
#include "stacktrace.h"
void some_buggy_function()
{
// use the throw_dbg macro to make throwing easier
throw_dbg(stacktrace::stack_aware_exception, "something is wrong!");
}
int main()
{
try
{
some_buggy_function();
}
catch(stacktrace::stack_aware_exception& e)
{
// use stream manipulators to set how to print exception
// stacktrace::shortexcept: prints e.what()
// stacktrace::longexcept: prints e.what(), and where it was thrown
// stacktrace::stacktrace: prints e.what(), where it was thrown, and a stacktrace
// some stacktrace elements from the constructor + stacktrace-generating functions will be printed
std::cout << stacktrace::stacktrace << e;
}
}
All you need to do is to implement a printer function (that takes a stacktrace::entry
and a std::ostream
). Be sure to not add a newline when printing, as that is already done for you.
#include "stacktrace.h"
int main()
{
// make use of the short type for a print function (optional, you can just stick the lambda in the call)
stacktrace::stack_printer printer = [](const entry& e, std::ostream& os)
{
os << "AT: [" << e.address << "] " << e.file << ':' << e.line << " (" << e.function << ')';
};
stacktrace::dump_stacktrace(10, printer, std::cout);
}
You can also get finer control over what happens to the stacktrace
#include "stacktrace.h"
int main()
{
stacktrace::pointer_stacktrace pointers = stacktrace::stacktrace(10); // capture the raw addresses of the stacktrace
stacktrace::symbol_stacktrace symbols = stacktrace::get_traced(pointers); // use symbols to make the stacktrace more readable
// dont call this if you are in release and have no symbols
stacktrace::dump_stacktrace(symbols, std::cout); // dump_stacktrace works with a pre-existing symbol stacktrace
}