Skip to content

Exceptions from EventRecordWrittenEventArgs are missing the original win32 error code #67702

@wokis

Description

@wokis

Description

One can retrieve a HResult error code from System.Diagnostics.Eventing.Reader.EventRecordWrittenEventArgs.EventException but it has no connection to the underlying win32 error code from the EvtNext function used (https://github.com/microsoft/referencesource/blob/master/System.Core/System/Diagnostics/Eventing/Reader/EventLogWatcher.cs#L228).

For example subscribing to an non existing log channel gives the error The handle is invalid. but the HResult code is -2146233088 (0x80131500). The win32 API error code for ERROR_INVALID_HANDLE is 6 (0x6).

Reproduction Steps

The MRE below subscribes to a non existing channel yielding an exception in the Watcher_EventRecordWritten handler.

private static void Test1()
{
    var query = new EventLogQuery(null, PathType.LogName, "<QueryList><Query Id=\"0\"><Select Path=\"non-existing-channel\">*</Select></Query></QueryList>");

    var watcher = new EventLogWatcher(query);
    watcher.EventRecordWritten += Watcher_EventRecordWritten;
    watcher.Enabled = true;
    EventLog.WriteEntry("dummy source", "Dummy test message");
    Thread.Sleep(1000 * 60);
    watcher.Enabled = false;
    Console.WriteLine("Test 1 completed");
}

private static void Watcher_EventRecordWritten(object sender, EventRecordWrittenEventArgs e)
{
    if (e.EventRecord == null) {
        Console.WriteLine(e.EventException.Message);
        Console.WriteLine(e.EventException.HResult);
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(string.Format("HRESULT:0x{0:X8}", e.EventException.HResult));
        Console.ForegroundColor = ConsoleColor.White;
    } else
    {
        Console.WriteLine(e.EventRecord.FormatDescription());
        e.EventRecord.Dispose();
    }
}

Expected behavior

The HResult from a EventRecordWrittenEventArgs.EventException should match the win32 error code returned from the EvtNext function (https://github.com/microsoft/referencesource/blob/5697c29004a34d80acdaf5742d7e699022c64ecd/System.Core/System/Diagnostics/Eventing/Reader/EventLogWatcher.cs#L228).

Actual behavior

The HResult from a EventRecordWrittenEventArgs.EventException does not match the actual error message.
All EventRecordWrittenEventArgs.EventException seem to return the same HResult and the EventException is of the base type Exception so there is no way to different between different errors.

Regression?

No response

Known Workarounds

No response

Configuration

.NET 6
Windows 10 21H2 (OS Build 19043.1586)
x64

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions