zoukankan      html  css  js  c++  java
  • Windows Internals 笔记——错误处理

    1.Windows函数检测到错误时,会使用一种名为“线程本地存储区”的机制将相应的错误代码与“主调线程”关联到一起。这种机制使得不同的线程能独立运行,不会出现相互干扰对方的错误代码的情况。

    2.GetLastError返回32位的错误代码表,每个错误有三种表示:一个消息ID、消息文本、和一个编号。函数失败后应立即调用GetLastError,否则很可能被改写。

    //
    // MessageId: ERROR_SUCCESS
    //
    // MessageText:
    //
    // The operation completed successfully.
    //
    #define ERROR_SUCCESS                    0L
    
    #define NO_ERROR 0L                                                 // dderror
    #define SEC_E_OK                         ((HRESULT)0x00000000L)
    
    //
    // MessageId: ERROR_INVALID_FUNCTION
    //
    // MessageText:
    //
    // Incorrect function.
    //
    #define ERROR_INVALID_FUNCTION           1L    // dderror
    
    //
    // MessageId: ERROR_FILE_NOT_FOUND
    //
    // MessageText:
    //
    // The system cannot find the file specified.
    //
    #define ERROR_FILE_NOT_FOUND             2L


     

    3.可以用FormatMessage函数来格式化输出错误信息。

    void OutputLastError(LPTSTR lpszFunctionName)
    {
        LPVOID lpMsgBuf;
        LPVOID lpDisplayBuf;
        DWORD dwErrorCode = GetLastError();
    
        FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER |
            FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL,
            dwErrorCode,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPTSTR)&lpMsgBuf,
            0, NULL);
    
        lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunctionName) + 40) * sizeof(TCHAR));
        StringCchPrintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(TCHAR), TEXT("%s failed with error %d : %s"), lpszFunctionName, dwErrorCode, lpMsgBuf);
    
        _tprintf((LPCTSTR)lpDisplayBuf);
    
        LocalFree(lpMsgBuf);
        LocalFree(lpDisplayBuf);
    }


    4.我们可以使用 void SetLastError(DWORD dwErrCode); 来设置错误代码,也可以创建自己的代码,32位字段的组成如下:

    需要注意的是第29位。

  • 相关阅读:
    阮一峰的网络日志
    解决Windows路径太长的目录以及文件名超长删除的问题
    LVM扩容根分区
    Centos7 搭建prometheus+Grafana监控
    python3 读取txt文件数据,绘制趋势图,matplotlib模块
    linux python3安装whl包时报错解决:is not a supported wheel on this platform
    堆排序
    nginx: [emerg] "upstream" directive is not allowed here in .../.../.../*.conf
    Github私有仓库使用设置
    AWK处理重复Hosts
  • 原文地址:https://www.cnblogs.com/zoneofmine/p/8087453.html
Copyright © 2011-2022 走看看