gpt4 book ai didi

c++ - 将 GetLastError() 转换为带有错误字符串的异常

转载 作者:行者123 更新时间:2023-11-30 02:24:33 26 4
gpt4 key购买 nike

这非常类似于: 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::string const char*(因为 std::system_error 需要 std::stringconst char*),这让我回到了错误被重置的同样问题。

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

最佳答案

您需要重写异常类构造函数,以便它将错误代码作为参数,因此错误代码:

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

关于c++ - 将 GetLastError() 转换为带有错误字符串的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45256281/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com