Recursive AI

Handle DOM event listener exceptions in C#

OneRender is a free, open-source HTML and CSS rendering library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Set page.Events.ListenerExceptionHandler to report errors from C# listeners without stopping dispatch. OneRender builds its own live DOM from HTML in your .NET process and runs neither a browser nor JavaScript.

Terminal
dotnet add package RecursiveAI.OneRender.Image

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using OneRender;
using OneRender.Image;
using OneRender.Interaction;
 
const string html = """
    <input type=checkbox id=alerts>
    """;
var fonts = FontProviders.CreateDefault();
var page = InteractivePage.Create(
    html, new HtmlPageOptions(fonts));
var events = page.Events;
events.ListenerExceptionHandler =
    (ex, e, _) => Console.WriteLine(
        $"{e.Type}: {ex.Message}");
var box = page.FindElement("alerts");
var target = EventTarget.Of(box);
events.AddEventListener(target, "click",
    _ => throw new InvalidOperationException(
        "Could not save"));
page.Click(box, 0);

The example is the full program below: unzip it and dotnet run. To run only the code above, paste it into Program.cs of a new dotnet new console project and dotnet run.

The error callback prints the event type and exception message:

Text
click: Could not save

The full program

The download adds a second click listener and listens for change to show what runs after the error.

C#
using OneRender;
using OneRender.Image;
using OneRender.Interaction;
 
const string html = """
    <input type=checkbox id=alerts>
    """;
var fonts = FontProviders.CreateDefault();
var page = InteractivePage.Create(
    html, new HtmlPageOptions(fonts));
var events = page.Events;
events.ListenerExceptionHandler =
    (ex, e, _) => Console.WriteLine(
        $"{e.Type}: {ex.Message}");
var box = page.FindElement("alerts");
var target = EventTarget.Of(box);
events.AddEventListener(target, "click",
    _ => throw new InvalidOperationException(
        "Could not save"));
events.AddEventListener(target, "click",
    _ => Console.WriteLine("Second listener ran"));
events.AddEventListener(target, "change",
    _ => Console.WriteLine("Change fired"));
page.Click(box, 0);
Console.WriteLine($"Checked: {page.IsChecked(box)}");
Text
click: Could not save
Second listener ran
Change fired
Checked: True

OperationCanceledException is different: it propagates to the caller instead of being reported to ListenerExceptionHandler.

Variations

Read the failure after dispatch. Replace the callback assignment with events.ListenerExceptionHandler = null;, then append these lines to the full program. They print 1 and Could not save:

C#
Console.WriteLine(events.ListenerExceptionCount);
Console.WriteLine(events.LastListenerException?.Message);

The short answer

Assign a callback to page.Events.ListenerExceptionHandler before handing input to the page. When a C# DOM listener throws, the callback receives the exception, the event being dispatched and the current target (the node or window whose listener threw). Dispatch then continues according to the same event rules as before. This lets a host report one failure without catching it around each Click or pointer input call.

Can I catch an event listener exception around dispatch?

Not for an ordinary listener exception in OneRender. Catching around page.Click won’t catch the sample’s InvalidOperationException because the dispatcher catches it and calls your reporting callback while dispatch is still in progress. This resembles the browser’s DOM dispatch rule: listener errors are reported instead of unwinding the caller. In OneRender, host cancellation is an exception to that rule: OperationCanceledException escapes the dispatch call. A try/catch inside the listener is still the right place to recover from a failure in that listener’s own operation.

Capture the values you need while your reporting callback is running. The event object is only valid during the call. For an error in a listener on a parent, the current target identifies that parent, even when the event originally started on a child. Log the type and current target rather than the original target alone if the goal is to locate the failing registration.

Do other listeners run if an event handler throws?

Yes, unless the event’s propagation flags say otherwise. In the full program the second click listener runs and the checkbox’s change event still fires. Throwing does not call PreventDefault and doesn’t mean the checkbox reverts to unchecked. If the listener calls PreventDefault on a cancelable click before throwing, that flag still applies. Likewise, a listener that already called StopImmediatePropagation doesn’t lose that flag when it throws.

Use the callback to record errors, not to signal that work should stop. The dispatcher also catches ordinary exceptions thrown by the reporting callback itself. If you don’t set a callback, it still tracks the failure count and latest exception on that dispatcher, but it doesn’t write a log for you. The count is cumulative for the dispatcher, not reset per event; use the callback when you need one report per failure.

All onerender recipes