Skip to content

Instantly share code, notes, and snippets.

@sergey-shambir
Created June 16, 2016 11:24
Show Gist options
  • Save sergey-shambir/12451454cb388fa990946f57099ad7df to your computer and use it in GitHub Desktop.
Save sergey-shambir/12451454cb388fa990946f57099ad7df to your computer and use it in GitHub Desktop.

Хорошая замена DWORD/int для кодов ошибок при работе с API ОС

Минимальный пример выдаёт “no such file or directory”:

#include <system_error>
#include <Windows.h>

void RaiseSystemError()
{
       std::error_code code(ERROR_PATH_NOT_FOUND, std::system_category());
       throw std::system_error(code);
}

int main()
{
       try
       {
             RaiseSystemError();
       }
       catch (const std::exception &ex)
       {
             std::cerr << ex.what() << std::endl;
       }
}

Сниппет возврата кода ошибки

std::error_code GetLastErrorCode()
{
       return std::error_code(::GetLastError(), std::system_category());
}

std::error_code CModuleVersionInfo::InitData()const
{
       if (!m_data)
       {
             // .. вызов Win32 API
       }

       return std::error_code(); // всё OK
}

Сниппет проверки кода ошибки

if (std::error_code err = InitData())
{
       throw std::system_error(err);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment