首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从GetLastError()返回的错误码中获取错误信息?

如何从GetLastError()返回的错误码中获取错误信息?
EN

Stack Overflow用户
提问于 2009-09-07 00:05:30
回答 8查看 177K关注 0票数 168

在Windows API调用之后,如何以文本形式获取最后一个错误消息?

GetLastError()返回整数值,而不是文本消息。

EN

回答 8

Stack Overflow用户

发布于 2013-06-30 12:32:18

//Returns the last Win32 error, in string format. Returns an empty string if there is no error.
std::string GetLastErrorAsString()
{
    //Get the error message ID, if any.
    DWORD errorMessageID = ::GetLastError();
    if(errorMessageID == 0) {
        return std::string(); //No error message has been recorded
    }
    
    LPSTR messageBuffer = nullptr;

    //Ask Win32 to give us the string version of that message ID.
    //The parameters we pass in, tell Win32 to create the buffer that holds the message for us (because we don't yet know how long the message string will be).
    size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                                 NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
    
    //Copy the error message into a std::string.
    std::string message(messageBuffer, size);
    
    //Free the Win32's string's buffer.
    LocalFree(messageBuffer);
            
    return message;
}
票数 183
EN

Stack Overflow用户

发布于 2009-09-07 06:21:24

MSDN提供了一些示例代码来演示如何同时使用FormatMessage()GetLastError()Retrieving the Last-Error Code

票数 22
EN

Stack Overflow用户

发布于 2009-09-07 00:10:38

FormatMessage会将GetLastError(http://msdn.microsoft.com/en-us/library/ms679360(VS.85%29.aspx)'s integer return )转换为文本消息。

票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1387064

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档