添加全局异常过滤生成转存储文件类

参考: http://tomlau-2000.blog.sohu.com/114084286.html

类:CrashDumper

CrashDumper.h

#ifndef _CRASH_DUMPER_H_
#define _CRASH_DUMPER_H_

#include <windows.h>

class CrashDumper
{
public:
    CrashDumper();
    ~CrashDumper();
    static bool _PlaceHolder();
private:
    LPTOP_LEVEL_EXCEPTION_FILTER m_OriginalFilter;
    static LONG WINAPI ExceptionFilter(struct _EXCEPTION_POINTERS* ExceptionInfo);
};

namespace
{
    const bool bPlaceHolder = CrashDumper::_PlaceHolder();
}

#endif
CrashDumper.cpp

#include <windows.h>
#include <tchar.h>
#include <dbghelp.h>
#include <string>

#include <QDebug>

#include "CrashDumper.h"

#ifdef UNICODE   

#     define tstring wstring    

#else      

#     define tstring string

#endif

#include <DbgHelp.h>
#pragma comment(lib, "dbghelp.lib")

CrashDumper dumper;
 
CrashDumper::CrashDumper()
{
    m_OriginalFilter = SetUnhandledExceptionFilter(ExceptionFilter);
}

CrashDumper::~CrashDumper()
{
    SetUnhandledExceptionFilter(m_OriginalFilter);
}

LONG WINAPI CrashDumper::ExceptionFilter(struct _EXCEPTION_POINTERS* ExceptionInfo)
{
    qDebug() << "exception filter";
    bool bDumpOK = false;

    TCHAR szPath[MAX_PATH];
    if(GetModuleFileName(NULL, szPath, sizeof(szPath)))
    {
        std::tstring strDumpFileName = szPath;
        strDumpFileName += TEXT(".dmp");
        HANDLE hFile = CreateFile(strDumpFileName.c_str(), FILE_ALL_ACCESS, 0, NULL, CREATE_ALWAYS, NULL, NULL);
        if (hFile != INVALID_HANDLE_VALUE)
        {
            MINIDUMP_EXCEPTION_INFORMATION exception_information;
            exception_information.ThreadId = GetCurrentThreadId();
            exception_information.ExceptionPointers = ExceptionInfo;
            exception_information.ClientPointers = TRUE;
            if (MiniDumpWriteDump(::GetCurrentProcess(),
                                  ::GetCurrentProcessId(),
                                  hFile, MiniDumpNormal, &exception_information, NULL, NULL))
            {
                bDumpOK = true;
            }

            CloseHandle(hFile);
        }
    }

    if (bDumpOK)
        qDebug() << "create dump file";

    qDebug() << "exception filter quit";
    return EXCEPTION_EXECUTE_HANDLER;
}

bool CrashDumper::_PlaceHolder() {return true;}
原文地址:https://www.cnblogs.com/jianc/p/2827507.html