1
這是非常相似的: Turning GetLastError() into an exception談到GetLastError函數()變成一個異常與錯誤字符串
我也希望能夠給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::string
或const char*
),這使我回到了同樣的問題,錯誤得到重置。
是否有一些優雅的解決方案,如何輕鬆拋出Win32錯誤,異常類捕獲GetLastError()
和能夠添加std::string
的任意信息?
IMO調用'GetLastError函數()'不應該在一個異常類「隱藏」。 GetLastError()應該在錯誤發生後立即被調用。我寧願放棄你的類提供的一點便利,只是將最後一個錯誤值作爲參數傳遞給'std :: sytem_error'。也許只有一行可寫,但代碼較少。 – zett42