我有一个Visual Studio 2008 C++项目,该项目在出现异常错误时使用Win32Exception
类。该Win32Exception
类看起来是这样的:将GetLastError()转换为异常
/// defines an exception based on Win32 error codes. The what() function will
/// return a formatted string returned from FormatMessage()
class Win32Exception : public std::runtime_error
{
public:
Win32Exception() : std::runtime_error(ErrorMessage(&error_code_))
{
};
virtual ~Win32Exception() { };
/// return the actual error code
DWORD ErrorCode() const throw() { return error_code_; };
private:
static std::string ErrorMessage(DWORD* error_code)
{
*error_code = ::GetLastError();
std::string error_messageA;
wchar_t* error_messageW = NULL;
DWORD len = ::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
*error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPWSTR>(&error_messageW),
0,
NULL);
if(NULL != error_messageW)
{
// this may generate a C4244 warning. It is safe to ignore.
std::copy(error_messageW,
error_messageW + len,
std::back_inserter(error_messageA));
::LocalFree(error_messageW);
}
return error_messageA;
};
/// error code returned by GetLastError()
DWORD error_code_;
}; // class Win32Exception
类效果很好它已经被使用,我想知道的是,如果有任何明显的情况下,这将失败,我应该知道什么情况。 。欢迎任何其他陷阱,注意事项或有关改进的一般建议。
请注意,boost代码库不适用于此代码。
如果你想知道,这个类也用于没有'FormatMessageA'的WindowsMobile。这就是为什么它从UNICODE转换为ASCII。 – PaulH 2010-12-17 22:12:20