From 3642552d0b1b928bf261f8008dc66f8f22c44a6b Mon Sep 17 00:00:00 2001 From: Larry Osterman Date: Tue, 8 Feb 2022 12:32:35 -0800 Subject: [PATCH] Improve the quality of the WinHTTP transport error message. (#3330) * Improved HTTP transport error message with Win32 error * Use std::unique_ptr to manage lifetime of error message --- .../src/http/winhttp/win_http_transport.cpp | 25 +++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/sdk/core/azure-core/src/http/winhttp/win_http_transport.cpp b/sdk/core/azure-core/src/http/winhttp/win_http_transport.cpp index 5c205d4a4..50fa62881 100644 --- a/sdk/core/azure-core/src/http/winhttp/win_http_transport.cpp +++ b/sdk/core/azure-core/src/http/winhttp/win_http_transport.cpp @@ -201,8 +201,29 @@ std::string GetHeadersAsString(Azure::Core::Http::Request const& request) void GetErrorAndThrow(const std::string& exceptionMessage) { DWORD error = GetLastError(); - throw Azure::Core::Http::TransportException( - exceptionMessage + " Error Code: " + std::to_string(error) + "."); + std::string errorMessage = exceptionMessage + " Error Code: " + std::to_string(error); + + char* errorMsg = nullptr; + if (FormatMessage( + FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_ALLOCATE_BUFFER, + GetModuleHandle("winhttp.dll"), + error, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + reinterpret_cast(&errorMsg), + 0, + nullptr) + != 0) + { + // Use a unique_ptr to manage the lifetime of errorMsg. + std::unique_ptr errorString(errorMsg, &LocalFree); + errorMsg = nullptr; + + errorMessage += ": "; + errorMessage += errorString.get(); + } + errorMessage += '.'; + + throw Azure::Core::Http::TransportException(errorMessage); } void WinHttpTransport::CreateSessionHandle(std::unique_ptr<_detail::HandleManager>& handleManager)