Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set HResult of exceptionForHR with message #479

Merged
merged 1 commit into from
Sep 4, 2024

Conversation

PrimalZed
Copy link
Contributor

@PrimalZed PrimalZed commented Aug 19, 2024

Issue

When using HRESULT.ThrowIfFailed with a non-null message, the returned exception might not have the correct HResult value.

Root Cause

When HRESULT.GetException is called with a non-null message, it creates a new exception with the same type as the exception from Marshal.GetExceptionForHR, expecting a constructor that takes a string message.

It does not set the HResult of this new exception.

Fix

Set HResult of new exception

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
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HResult property had protected set prior to .NET Core 3.0

@@ -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();
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is the particular hresult I found the issue with. It returns a FileLoadException which has default hresult COR_E_FILELOAD 0x80131621, which differs from this win32HResult value 0x80070020

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dahall dahall merged commit a47f6d5 into dahall:master Sep 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants