Alternative for Marshal.GetExceptionCode()?

Viewed 479

Marshal.GetExceptionCode() has been obsoleted, and the message does not suggest a way forward.

at the moment I use this in the following opensource project:

https://github.com/dbones-labs/auditable/blob/master/src/Auditable/AuditableContext.cs#L143

the idea is, if the client code/app within a using block throws an exception it should not write a log.

However, the project code only has a using statement to figure out if it should react or not.

what is the alternative to this? (without changeing the API for the calling code)

example use of the API https://dbones-labs.github.io/auditable/quick-examples/aspnet-example.html#3-add-some-auditable-logs

1 Answers

From a quick test it seems you can use Marshal.GetExceptionPointers():

public class MyDisposable : IDisposable
{
    public void Dispose()
    {
        var ptr = Marshal.GetExceptionPointers();
        Console.WriteLine(ptr);
    }
}

try
{
    using (new MyDisposable())
    {
    }

    using (new MyDisposable())
    {
        throw new Exception();
    }
}
catch (Exception)
{
}

using (new MyDisposable())
{
}

It is non-zero if there is an Exception "in the air".

Note that Marshal.GetExceptionPointers() was always present in .NET Framework but was reintroduced in .NET Core only >= 3.0. So for .NET Core 1.0-2.2 you'll need to use Marshal.GetExceptionCode()`.

Related