Skip to content

Commit

Permalink
Add last_error_saver
Browse files Browse the repository at this point in the history
Signed-off-by: Simon Rozman <[email protected]>
  • Loading branch information
rozmansi committed Mar 15, 2024
1 parent 9da457a commit 0559794
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
32 changes: 30 additions & 2 deletions include/WinStd/Common.h
Original file line number Diff line number Diff line change
Expand Up @@ -1517,6 +1517,35 @@ namespace winstd
error_type m_num; ///< Numeric error code
};

///
/// Saves GetLastError and restores SetLastError when going out of scope
///
class last_error_saver
{
public:
///
/// Saves the calling thread's last-error code value.
///
/// \sa [GetLastError function](https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror)
///
last_error_saver(_In_ DWORD error = GetLastError()) :
m_error(error)
{}

///
/// Sets the last-error code for the calling thread.
///
/// \sa [SetLastError function](https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-setlasterror)
///
~last_error_saver()
{
SetLastError(m_error);
}

protected:
DWORD m_error;
};

///
/// Windows runtime error
///
Expand Down Expand Up @@ -1580,7 +1609,7 @@ namespace winstd
///
static std::string message(_In_ error_type num, _In_opt_ DWORD dwLanguageId = 0)
{
error_type runtime_num = GetLastError();
last_error_saver last_error_save;
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.
Expand All @@ -1589,7 +1618,6 @@ namespace winstd
sprintf(wstr, num >= 0x10000 ? L"Error 0x%X" : L"Error %u", num);
std::string str;
WideCharToMultiByte(CP_UTF8, 0, wstr, str, NULL, NULL);
SetLastError(runtime_num);
return str;
}
};
Expand Down
3 changes: 1 addition & 2 deletions include/WinStd/Win.h
Original file line number Diff line number Diff line change
Expand Up @@ -1590,9 +1590,8 @@ namespace winstd
return;

revert:
DWORD dwResult = GetLastError();
last_error_saver last_error_save;
RevertToSelf();
SetLastError(dwResult);
}
};

Expand Down

0 comments on commit 0559794

Please sign in to comment.