【问题标题】:Problem with GetLastError API on windows 7Windows 7 上的 GetLastError API 问题
【发布时间】:2010-02-17 07:21:43
【问题描述】:

我有一个与服务器交互的应用程序。如果服务器关闭,那么我将得到ERROR_WINHTTP_CANNOT_CONNECT 我正在使用getLastError() API 来获取此错误代码,我正在处理此错误代码以向用户显示正确的错误消息。该程序在 Windows 2003 中运行良好。当我尝试使用 Windows7 时,我没有收到任何错误,getLastError() API 每次都会返回 0,即使发生错误也是如此。我正在使用 C++ 作为编程语言。

提前致谢

桑杜

【问题讨论】:

    标签: winapi windows-7 getlasterror


    【解决方案1】:

    如果您在失败和调用 GetLastError() 之间进行任何 Windows API 调用,则该 API 调用成功时错误代码可能会重置为 0。

    您需要在失败后立即调用 GetLastError(),并保存该值,而不是尝试等待并稍后再调用 GetLastError()。

    【讨论】:

      【解决方案2】:

      我在 Windows 2003 和 Windows 7 中观察到 GetLastError API 的不同行为。 以下是我的观察细节

      在 Windows 2003 中:

      示例代码:

      WinHttpOpen () – 成功完成

      Winhttpconnect() – 由于某些原因,此 API 失败,例如错误代码 12029

      GetLastErrorCode() – 按预期返回错误代码 12029

      WinHttpCloseHandle(hOpen); - HttpOpen 的关闭句柄,成功完成

      GetLastErrorCode() – 返回错误代码 12029

      在 Windows 7 中

      示例代码:

      WinHttpOpen () – 成功完成

      Winhttpconnect() – 此 API 由于某些原因失败,例如错误代码 12029

      GetLastErrorCode() – 按预期返回错误代码 12029

      WinHttpCloseHandle(hOpen); - HttpOpen 的关闭句柄,成功完成

      GetLastErrorCode() – 返回错误代码 0 // 查看与 Windows 2003 示例的区别,在 Windows 2003 上,此 API 返回最后一个错误,即 1209

      【讨论】:

        【解决方案3】:

        Microsoft 对此行为的回答

        The rules for GetLastError are:
        
        •   If the WinHttp API returns error (for example WinHttpIsHostInProxyBypassList, http://msdn.microsoft.com/en-us/library/ee861268(VS.85).aspx) this is the error and GetLastError should *NOT* be called.
        o   If GetLastError() is called, regardless of the success or failure of the API, the returned value is unpredictable and may change between Windows versions, Service Packs, or even between runs.
        •   If the WinHttp API returns BOOL (for example WinHttpSetTimeouts, http://msdn.microsoft.com/en-us/library/aa384116(VS.85).aspx), it indicates failure by returning FALSE. If the caller is interested in the detailed error, (s)he should call GetLastError(). Note that GetLastError should be called *if and only if* the API failed.
        o   If GetLastError() is called when the API succeded (returned anything but FALSE), the returned value is unpredictable and may change between Windows versions, Service Packs, or even between runs. 
        •   If the WinHttp API returns HINTERNET (pseudo handle) the rules are exactly the same, except failure is indicated by returning NULL. 
        o   If GetLastError() is called when the API succeded (returned anything but NULL), the returned value is unpredictable and may change between Windows versions, Service Packs, or even between runs. 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-11-29
          • 2012-01-04
          • 2013-05-26
          • 2015-03-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多