DotNetDupe 4.0.6
C++17/20 Implementation of the .NET Base Class Library (BCL)
Loading...
Searching...
No Matches
Win32Exception.cpp
Go to the documentation of this file.
1#include "pch.h"
3#include "System/String.h"
4
5#if defined(_WIN32)
6#include <windows.h>
7#include "Win32Internal.h"
8using namespace DotNetDupe::System::Internal;
9#else
10#include <cstring>
11#include <cerrno>
12#endif
13
14namespace DotNetDupe {
15 namespace System {
16 namespace ComponentModel {
17
18 static String FormatErrorMessage(int nErrorCode) {
20#if defined(_WIN32)
21 LPWSTR lpMsgBuf = nullptr;
22 DWORD dwLen = ::FormatMessageW(
23 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
24 nullptr,
25 static_cast<DWORD>(nErrorCode),
26 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
27 reinterpret_cast<LPWSTR>(&lpMsgBuf),
28 0,
29 nullptr
30 );
31
33 if (dwLen > 0 && lpMsgBuf != nullptr) {
34 while (dwLen > 0 && (lpMsgBuf[dwLen - 1] == L'\r' || lpMsgBuf[dwLen - 1] == L'\n')) {
35 lpMsgBuf[--dwLen] = L'\0';
36 }
37 std::string sUtf8 = StringConvertInternal::WCharToUtf8(lpMsgBuf);
38 ::LocalFree(lpMsgBuf);
39 return String(sUtf8.c_str());
40 }
41 return String("Unknown system error");
42#else
43 const char* pchErr = std::strerror(nErrorCode);
44 return pchErr ? String(pchErr) : String("Unknown system error");
45#endif
46 }
47
49#if defined(_WIN32)
50 : Win32Exception(static_cast<int>(::GetLastError()))
51#else
52 : Win32Exception(errno)
53#endif
54 {
56 }
57
58 Win32Exception::Win32Exception(int nNativeErrorCode)
59 : SystemException(FormatErrorMessage(nNativeErrorCode)), m_nNativeErrorCode(nNativeErrorCode)
60 {
62 }
63
64 Win32Exception::Win32Exception(int nNativeErrorCode, const String& sMessage)
65 : SystemException(sMessage), m_nNativeErrorCode(nNativeErrorCode)
66 {
68 }
69
71#if defined(_WIN32)
72 : SystemException(sMessage), m_nNativeErrorCode(static_cast<int>(::GetLastError()))
73#else
74 : SystemException(sMessage), m_nNativeErrorCode(errno)
75#endif
76 {
78 }
79
80 }
81 }
82}
High-performance UTF-8 / UTF-16 string manipulation class mirroring .NET System.String.
Exception thrown for a Win32 or platform-native error code.
Win32Exception()
Initializes a new instance of the Win32Exception class with the last Win32/native error code.
static std::string WCharToUtf8(const wchar_t *pWStr)
Represents text as a sequence of UTF-8 code units with culture-invariant operations.
Definition String.h:74
String()
Initializes a new instance of the String class to an empty string.
Definition String.cpp:64
SystemException()
Initializes a new instance of the SystemException class with a default message.
Definition Exception.cpp:48
static String FormatErrorMessage(int nErrorCode)