From 34b3bf6c05afd55ca6c5e6e6c05330d7ad9ea41a Mon Sep 17 00:00:00 2001 From: Matt Lyons Date: Thu, 29 Aug 2024 09:06:56 -0500 Subject: [PATCH] Log exception messages on .NET 6+ when dynamic library loading fails (#204) --- source/icu.net/NativeMethods/NativeMethods.cs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/source/icu.net/NativeMethods/NativeMethods.cs b/source/icu.net/NativeMethods/NativeMethods.cs index cc6ab483..2cca9955 100644 --- a/source/icu.net/NativeMethods/NativeMethods.cs +++ b/source/icu.net/NativeMethods/NativeMethods.cs @@ -347,14 +347,16 @@ private static IntPtr GetIcuLibHandle(string basename, int icuVersion) var libPath = string.IsNullOrEmpty(_IcuPath) ? libName : Path.Combine(_IcuPath, libName); #if NET6_0_OR_GREATER + string exceptionErrorMessage = null; loadMethod = "NativeLibrary.Load"; try { handle = NativeLibrary.Load(libPath); } - catch (DllNotFoundException) + catch (DllNotFoundException ex) { handle = IntPtr.Zero; + exceptionErrorMessage = ex.Message; } #else if (IsWindows) @@ -385,14 +387,16 @@ private static IntPtr GetIcuLibHandle(string basename, int icuVersion) lastError = Marshal.GetLastWin32Error(); #if NET6_0_OR_GREATER + if (!string.IsNullOrEmpty(exceptionErrorMessage)) + exceptionErrorMessage = $" ({exceptionErrorMessage})"; var errorMsg = IsWindows - ? new Win32Exception(lastError).Message - : $"{lastError}"; + ? $"{new Win32Exception(lastError).Message}{exceptionErrorMessage}" + : $"{lastError}({exceptionErrorMessage})"; #else var errorMsg = IsWindows ? new Win32Exception(lastError).Message : IsMac - ? $"{lastError}" + ? $"{lastError} (macOS loading requires .NET 6 or greater)" : $"{lastError} ({dlerror()})"; #endif Trace.WriteLineIf(lastError != 0, $"Unable to load [{libPath}]. Error: {errorMsg}");