Exception类用于异常数据的储存和获取
头文件
#ifndef MUDUO_BASE_EXCEPTION_H
#define MUDUO_BASE_EXCEPTION_H
#include <muduo/base/Types.h>
#include <exception>
namespace muduo
{
class Exception : public std::exception
{
public:
explicit Exception(const char* what);
explicit Exception(const string& what);
virtual ~Exception() throw();
virtual const char* what() const throw();
const char* stackTrace() const throw(); //返回异常数据栈
private:
void fillStackTrace();
string message_;
string stack_;
};
}
cpp文件
#include <execinfo.h>
#include <stdlib.h>
using namespace muduo;
Exception::Exception(const char* msg)
: message_(msg)
{
fillStackTrace();
}
Exception::Exception(const string& msg)
: message_(msg)
{
fillStackTrace();
}
Exception::~Exception() throw ()
{
}
const char* Exception::what() const throw()
{
return message_.c_str(); //返回当前异常内容指针
}
const char* Exception::stackTrace() const throw()
{
return stack_.c_str(); //返回所有异常内容指针
}
void Exception::fillStackTrace()
{
const int len = 200;
void* buffer[len];
int nptrs = ::backtrace(buffer, len); //系统调用,用于返回发送异常的函数和之前函数的调用总个数,储存其函数指针列表
char** strings = ::backtrace_symbols(buffer, nptrs);//将函数指针列表查询返回为具体函数信息字符串
if (strings)
{
for (int i = 0; i < nptrs; ++i) //字符串拆分并合并到stack中
{
// TODO demangle funcion name with abi::__cxa_demangle
stack_.append(strings[i]);
stack_.push_back('\n');
}
free(strings);
}
}