CppCommon  1.0.4.1
C++ Common Library
system_error.cpp
Go to the documentation of this file.
1 
9 #include "errors/system_error.h"
10 
11 #include "string/encoding.h"
12 
13 #if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
14 #include "string/format.h"
15 #include <errno.h>
16 #include <string.h>
17 #elif defined(_WIN32) || defined(_WIN64)
18 #include <windows.h>
19 #endif
20 
21 namespace CppCommon {
22 
23 int SystemError::GetLast() noexcept
24 {
25 #if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
26  return errno;
27 #elif defined(_WIN32) || defined(_WIN64)
28  return GetLastError();
29 #endif
30 }
31 
32 void SystemError::SetLast(int error) noexcept
33 {
34 #if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
35  errno = error;
36 #elif defined(_WIN32) || defined(_WIN64)
37  return SetLastError(error);
38 #endif
39 }
40 
41 void SystemError::ClearLast() noexcept
42 {
43  SetLast(0);
44 }
45 
46 std::string SystemError::Description(int error)
47 {
48  const int capacity = 1024;
49 #if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
50  char buffer[capacity];
51 #if defined(__APPLE__) || defined(__CYGWIN__)
52  int result = strerror_r(error, buffer, capacity);
53  if (result != 0)
54 #else
55  char* result = strerror_r(error, buffer, capacity);
56  if (result == nullptr)
57 #endif
58  return format("Cannot convert the given system error code to the system message - {}", error);
59  else
60  return std::string(buffer);
61 #elif defined(_WIN32) || defined(_WIN64)
62  WCHAR buffer[capacity];
63  DWORD size = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, capacity, nullptr);
64  return Encoding::ToUTF8((size >= 2) ? std::wstring(buffer, (size - 2)) : std::wstring(L"Unknown system error!"));
65 #endif
66 }
67 
68 } // namespace CppCommon
static std::string ToUTF8(std::wstring_view wstr)
Convert system wide-string to UTF-8 encoded string.
Definition: encoding.cpp:19
static void ClearLast() noexcept
Clear the last system error code.
static int GetLast() noexcept
Get the last system error code.
static std::string Description()
Convert the last system error code to the system error description.
Definition: system_error.h:52
static void SetLast(int error) noexcept
Set the last system error code.
Encoding utilities definition.
Format string definition.
C++ Common project definitions.
Definition: token_bucket.h:15
std::string format(fmt::format_string< T... > pattern, T &&... args)
Format string.
Definition: format.inl:12
System error definition.