samedi 22 juillet 2017

Turning GetLastError() into an exception with Error string

This is very similar to: Turning GetLastError() into an exception

I also want to be able to add an std::string to the error:

class Win32Exception2 : public std::system_error
{
public:
    Win32Exception2(std::string ErrorDesc) : std::system_error(GetLastError(), std::system_category(), ErrorDesc)
    {
    }
};

The problem is that at least in DEBUG builds of VS2015 the construction of std::string resets GetLastError(). So by the time the Win32Exception calls GetLastError() it always gets zero/no error.

I could use const char*, but I also want to use std::wstring, which means I need to convert it to std::string or const char* (because the std::system_error expects std::string or const char*), and that leads me back to the same problem that the error gets reset.

Is there some elegant solution on how to throw Win32 errors easily, having the exception class capture GetLastError() and being able to add arbitrary info with std::string's?

Aucun commentaire:

Enregistrer un commentaire