How do you use std::system_error with GetLastError?

前端 未结 2 1080
Happy的楠姐
Happy的楠姐 2021-01-01 18:39

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?

相关标签:
2条回答
  • 2021-01-01 19:22

    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.

    0 讨论(0)
  • 2021-01-01 19:26

    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.

    0 讨论(0)
提交回复
热议问题