Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use std::system_error with GetLastError?

Tags:

c++

c++11

winapi

If I call a Win32 function that reports errors via GetLastError, for example RegisterClassEx, how do I throw a std::system_error for that error?

like image 744
Michael Marcin Avatar asked Apr 06 '13 19:04

Michael Marcin


People also ask

What is std :: System_error?

std::system_error is the type of the exception thrown by various library functions (typically the functions that interface with the OS facilities, e.g. the constructor of std::thread) when the exception has an associated std::error_code, which may be reported.

What does GetLastError return?

The GetLastError function returns the calling thread's last-error code value.

How do I contact GetLastError?

From the GetLastError() documentation: "To obtain an error string for system error codes, use the FormatMessage() function.". See the Retrieving the Last-Error Code example on MSDN.

How do I get error messages in C++?

C++ perror() The perror() function in C++ prints the error message to stderr based on the error code currently stored in the system variable errno.


2 Answers

Check on the value of GetLastError() like

DWORD dwErrVal = GetLastError();
std::error_code ec (dwErrVal, std::system_category());
throw std::system_error(ec, "Exception occurred");

See here for error_code and here for std::system_error.

like image 198
bash.d Avatar answered Sep 21 '22 11:09

bash.d


Be aware that comparing a std::error_code in the category of std::system_category() doesn't generally work with the std::errc enumeration constants depending on your vendor. E.g.

std::error_code(ERROR_FILE_NOT_FOUND, std::system_category()) != std::errc::no_such_file_or_directory)

Certain vendors require using std::generic_category() for that to work.

In MinGW std::error_code(ERROR_FILE_NOT_FOUND, std::system_category()).message() won't give you the correct message.

For a truly portable and robust solution I would recommend subclassing both std::system_error and std::system_category to windows_error and windows_category and implement the correct functionality yourself. YMMV, VS2017 has been reported to work as one would expect.

like image 22
Rian Hunter Avatar answered Sep 22 '22 11:09

Rian Hunter