---
title: "Handle DOM event listener exceptions in C#"
url: https://recursiveai.org/onerender/cookbook/handle-live-dom-event-listener-exceptions/
description: "Report errors from C# listeners on live HTML with OneRender’s ListenerExceptionHandler, without stopping the rest of dispatch or canceling the default action."
version: "1.6.1"
---

# 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.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneRender.Image) · [GitHub](https://github.com/recursive-ai-oss/onerender-csharp) · [Docs](https://recursiveai.org/onerender/docs/) · [Download example (.zip)](https://recursiveai.org/onerender/cookbook/handle-live-dom-event-listener-exceptions/handle-live-dom-event-listener-exceptions.zip)

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.

```shell
dotnet add package RecursiveAI.OneRender.Image
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
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](https://recursiveai.org/onerender/cookbook/handle-live-dom-event-listener-exceptions/handle-live-dom-event-listener-exceptions.zip) 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.

```csharp
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`:

```csharp
Console.WriteLine(events.ListenerExceptionCount);
Console.WriteLine(events.LastListenerException?.Message);
```

## Related recipes

- [Click a rendered HTML element in C#](https://recursiveai.org/onerender/cookbook/activate-html-control-with-programmatic-click/)
- [Hit-test rendered HTML and dispatch events](https://recursiveai.org/onerender/cookbook/hit-testing-events/)

## 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](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent#exceptions): 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.
