赞
踩
依赖win10库文件 DbgHelp.dll 或者 DbgHelp.lib
#ifndef CRASH_H
#define CRASH_H
//异常处理
#include <Windows.h>
#include <DbgHelp.h>
#include <iostream>
#include <sstream>
#include <iomanip>
/*!
* \brief 整数转16进制字符串
* \param s_src
* \param len
* \return
*/
static std::string convertToBase16Str(const unsigned char* s_src, int len)
{
std::string str("0x");
std::stringstream ioss;
int a = 0x1234;
char b = static_cast<char>(a);
if (b == 0x12)
{
//cout << "大端模式" << endl;
for (int i = 0; i < len; i++) {
ioss << std::hex << std::setw(2) << std::setfill('0') << (int)s_src[i];
str.append(ioss.str());
ioss.str("");
}
}
else if (b == 0x34)
{
//cout << "小端模式" << endl;
int i = len-1;
while(i>=0) {
ioss << std::hex /*<< std::setw(2) << std::setfill('0')*/ << (int)s_src[i--];
str.append(ioss.str());
ioss.str("");
}
}
ioss.clear();
return str;
}
//异常捕获
static LONG ApplicationCrashHandler(EXCEPTION_POINTERS *pException)
{
wchar_t szFileName[MAX_PATH] = { 0 };
wchar_t szVersion[] = L"DumpFile";
SYSTEMTIME stLocalTime;
GetLocalTime(&stLocalTime);
//wsprintf in user32.lib
wsprintf(szFileName, L"%s-%04d%02d%02d-%02d%02d%02d.dmp",
szVersion, stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay,
stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond);
//创建 Dump 文件
HANDLE hDumpFile = CreateFile(szFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hDumpFile != INVALID_HANDLE_VALUE)
{
//Dump信息
MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
dumpInfo.ExceptionPointers = pException;
dumpInfo.ThreadId = GetCurrentThreadId();
dumpInfo.ClientPointers = TRUE;
//写入Dump文件内容
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);
}
//错误输出
EXCEPTION_RECORD* record = pException->ExceptionRecord;
std::string errCode ="ErrCode:"+ convertToBase16Str((const unsigned char*)&record->ExceptionCode,sizeof(record->ExceptionCode));
std::string errAddr ="ErrAddr:"+ convertToBase16Str((const unsigned char*)&record->ExceptionAddress,sizeof(record->ExceptionAddress));
std::cout<<("!!!---------------App Crash ----------------!!! \n");
std::cout<<"errCode : "<<errCode<<std::endl;
std::cout<<"errAddr : "<<errAddr<<std::endl;
fflush(stdout);
return EXCEPTION_EXECUTE_HANDLER;
}
//注册异常处理函数
static int crashInit = []()->int{
std::cout<<"----------- Register crash hander -----------"<<std::endl;
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);
return 0;
}();
#endif // CRASH_H
QMAKE_CXXFLAGS_RELEASE = $$QMAKE_CFLAGS_RELEASE_WITH_DEBUGINFO
QMAKE_LFLAGS_RELEASE = $$QMAKE_LFLAGS_RELEASE_WITH_DEBUGINFO
LIBS += -lDbgHelp -luser32
#include <QApplication>
#include <QDebug>
#include<iostream>
#include "CrashHander.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
std::vector<int> v(5);
std::cout << v.at(10); // vector::at() 抛出 std::out_of_range
return a.exec();
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。