Skip to content

Commit

Permalink
Set hresult of exceptionForHR with supplied message (#479)
Browse files Browse the repository at this point in the history
  • Loading branch information
PrimalZed authored Sep 4, 2024
1 parent 1638eb9 commit a47f6d5
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
10 changes: 7 additions & 3 deletions PInvoke/Shared/WinError/HRESULT.cs
Original file line number Diff line number Diff line change
Expand Up @@ -700,16 +700,20 @@ public int CompareTo(object? obj)
if (!Failed) return null;

var exceptionForHR = Marshal.GetExceptionForHR(_value, new IntPtr(-1));
if (exceptionForHR?.GetType() == typeof(COMException))
if (exceptionForHR is null) return null;
if (exceptionForHR.GetType() == typeof(COMException))
{
return Facility == FacilityCode.FACILITY_WIN32
? string.IsNullOrEmpty(message) ? new Win32Exception(Code) : new Win32Exception(Code, message)
: new COMException(message ?? exceptionForHR.Message, _value);
}
if (!string.IsNullOrEmpty(message))
{
var constructor = exceptionForHR?.GetType().GetConstructor(new Type[] { typeof(string) });
exceptionForHR = constructor?.Invoke(new object[] { message! }) as Exception;
var constructor = exceptionForHR.GetType().GetConstructor(new Type[] { typeof(string) })!;
exceptionForHR = constructor.Invoke(new object[] { message! }) as Exception;
# if NETCOREAPP3_0_OR_GREATER
exceptionForHR!.HResult = _value;
#endif
}
return exceptionForHR;
}
Expand Down
4 changes: 4 additions & 0 deletions UnitTests/PInvoke/Shared/WinError/HRESULTTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ public void GetExceptionTest()
Assert.That(new HRESULT(HRESULT.CO_E_ATTEMPT_TO_CREATE_OUTSIDE_CLIENT_CONTEXT).GetException(), Is.TypeOf<COMException>());
Assert.That(new HRESULT(HRESULT.E_INVALIDARG).GetException(), Is.TypeOf<ArgumentException>());
Assert.That(new HRESULT(HRESULT.E_INVALIDARG).GetException("Bad"), Has.Message.EqualTo("Bad"));
#if NETCOREAPP3_0_OR_GREATER
var win32HResult = new Win32Error(Win32Error.ERROR_SHARING_VIOLATION).ToHRESULT();
Assert.That(win32HResult.GetException("Bad"), Has.Property(nameof(Exception.HResult)).EqualTo(win32HResult));
#endif
}

[Test()]
Expand Down

0 comments on commit a47f6d5

Please sign in to comment.