Bitcoin Core  27.99.0
P2P Digital Currency
syserror.cpp
Go to the documentation of this file.
1 // Copyright (c) 2020-2022 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #if defined(HAVE_CONFIG_H)
7 #endif
8 
9 #include <tinyformat.h>
10 #include <util/syserror.h>
11 
12 #include <cstring>
13 #include <string>
14 
15 #if defined(WIN32)
16 #include <windows.h>
17 #include <locale>
18 #include <codecvt>
19 #endif
20 
21 std::string SysErrorString(int err)
22 {
23  char buf[1024];
24  /* Too bad there are three incompatible implementations of the
25  * thread-safe strerror. */
26  const char *s = nullptr;
27 #ifdef WIN32
28  if (strerror_s(buf, sizeof(buf), err) == 0) s = buf;
29 #else
30 #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
31  s = strerror_r(err, buf, sizeof(buf));
32 #else /* POSIX variant always returns message in buffer */
33  if (strerror_r(err, buf, sizeof(buf)) == 0) s = buf;
34 #endif
35 #endif
36  if (s != nullptr) {
37  return strprintf("%s (%d)", s, err);
38  } else {
39  return strprintf("Unknown error (%d)", err);
40  }
41 }
42 
43 #if defined(WIN32)
44 std::string Win32ErrorString(int err)
45 {
46  wchar_t buf[256];
47  buf[0] = 0;
48  if(FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
49  nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
50  buf, ARRAYSIZE(buf), nullptr))
51  {
52  return strprintf("%s (%d)", std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().to_bytes(buf), err);
53  }
54  else
55  {
56  return strprintf("Unknown error (%d)", err);
57  }
58 }
59 #endif
std::string SysErrorString(int err)
Return system error string from errno value.
Definition: syserror.cpp:21
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162