【问题标题】:Turning GetLastError() into an exception with Error string将 GetLastError() 变成带有错误字符串的异常
【发布时间】:2017-07-22 15:34:43
【问题描述】:

这非常类似于: Turning GetLastError() into an exception

我还希望能够在错误中添加std::string

class Win32Exception : public std::system_error
{
public:
    Win32Exception(std::string ErrorDesc) : std::system_error(GetLastError(), std::system_category(), ErrorDesc)
    {
    }
};

问题在于,至少在 VS2015 的 DEBUG 版本中,std::string 的构造会重置 GetLastError()。因此,当 Win32Exception 调用 GetLastError() 时,它总是得到零/无错误。

我可以使用const char*,但我也想使用std::wstring,这意味着我需要将其转换为std::stringconst char*(因为std::system_error 需要std::stringconst char*) ,这导致我回到错误被重置的相同问题。

关于如何轻松抛出 Win32 错误,是否有一些优雅的解决方案,让异常类捕获 GetLastError() 并能够使用 std::string 添加任意信息?

【问题讨论】:

  • IMO 对 GetLastError() 的调用不应“隐藏”在异常类中。 GetLastError() 应该在错误情况发生后立即调用。我宁愿放弃你的类提供的一点便利,只是将最后一个错误值作为参数传递给std::sytem_error。也许多写一行代码,但不那么脆弱。

标签: c++ string c++11 winapi exception


【解决方案1】:

你需要重写异常类的构造函数,所以它将错误代码作为参数,所以错误代码:

Win32Exception
(
    char const * const psz_description
,   ::DWORD const      error_code = ::GetLastError()
)
:   std::system_error(error_code, std::system_category(), psz_description)
{
}

【讨论】:

    猜你喜欢
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    相关资源
    最近更新 更多