COM: Use FormatMessage when no msg provided for com_runtime_error

Signed-off-by: Simon Rozman <simon@rozman.si>
This commit is contained in:
Simon Rozman 2025-01-20 16:22:02 +01:00
parent 34d5dc23df
commit b7de081788

View File

@ -27,13 +27,21 @@ namespace winstd
class com_runtime_error : public num_runtime_error<HRESULT> class com_runtime_error : public num_runtime_error<HRESULT>
{ {
public: public:
///
/// Constructs an exception
///
/// \param[in] num Windows error code
///
com_runtime_error(_In_ error_type num) : num_runtime_error<HRESULT>(num, message(num))
{}
/// ///
/// Constructs an exception /// Constructs an exception
/// ///
/// \param[in] num COM error code /// \param[in] num COM error code
/// \param[in] msg Error message /// \param[in] msg Error message
/// ///
com_runtime_error(_In_ error_type num, _In_ const std::string& msg) : num_runtime_error<HRESULT>(num, msg) com_runtime_error(_In_ error_type num, _In_ const std::string& msg) : num_runtime_error<HRESULT>(num, msg + ": " + message(num))
{ {
} }
@ -43,9 +51,29 @@ namespace winstd
/// \param[in] num COM error code /// \param[in] num COM error code
/// \param[in] msg Error message /// \param[in] msg Error message
/// ///
com_runtime_error(_In_ error_type num, _In_opt_z_ const char* msg = nullptr) : num_runtime_error<HRESULT>(num, msg) com_runtime_error(_In_ error_type num, _In_opt_z_ const char* msg) : num_runtime_error<HRESULT>(num, std::string(msg) + ": " + message(num))
{ {
} }
protected:
///
/// Returns a user-readable Windows error message.
/// As std::exception messages may only be char*, we use UTF-8 by convention.
///
/// \sa [FormatMessage function](https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-formatmessage)
///
static std::string message(_In_ error_type num, _In_opt_ DWORD dwLanguageId = 0)
{
std::wstring wstr;
if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, num, dwLanguageId, wstr, NULL)) {
// Stock Windows error messages contain CRLF. Well... Trim all the trailing white space.
wstr.erase(wstr.find_last_not_of(L" \t\n\r\f\v") + 1);
} else
sprintf(wstr, num >= 0x10000 ? L"Error 0x%X" : L"Error %u", num);
std::string str;
WideCharToMultiByte(CP_UTF8, 0, wstr, str, NULL, NULL);
return str;
}
}; };
/// @} /// @}