Recursive AI

Read JavaScript exception stack frames in C#

OneEcma is a free, open-source JavaScript interpreter for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Read JsException.Frames for a local script’s call stack.

Terminal
dotnet add package RecursiveAI.OneEcma

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

C#
using RecursiveAI.OneEcma;
var js = "function fail(){throw new Error()}";
try {
    new ScriptEngine().Evaluate(
        js + "\nfail();", "demo.js");
} catch (JsException error) {
    foreach (var frame in error.Frames) {
        var (line, col) = frame.Position;
        var file = frame.Source.Name;
        Console.WriteLine(
            ($"{file}:{line}:{col} " +
             frame.Function).TrimEnd());
    }
}

Unzip the example, then dotnet run.

Prints:

Text
demo.js:1:23 fail
demo.js:2:1

The full program

C#
using RecursiveAI.OneEcma;
 
var script = """
    function fail() { throw new Error(); }
    function run() { fail(); }
    run();
    """;
var engine = new ScriptEngine();
try
{
    engine.Evaluate(script, "demo.js");
}
catch (JsException error)
{
    foreach (var frame in error.Frames)
    {
        var (line, col) = frame.Position;
        var file = frame.Source.Name;
        var name = frame.IsTopLevel ? "<top-level>" : frame.Function;
        Console.WriteLine($"{file}:{line}:{col} {name}");
    }
}
Text
demo.js:1:25 fail
demo.js:2:18 run
demo.js:3:1 <top-level>

The stack starts at fail, where the error object is created. It ends at the top-level call. The full program also calls fail through run. The top-level frame’s Function is empty, so the program prints <top-level> instead. demo.js is just the source name given to Evaluate, not a file you need to create.

Variations

To see what happens when the thrown value isn’t an Error object, append this to the snippet at the top:

C#
try { new ScriptEngine().Evaluate("throw 7"); }
catch (JsException error)
{
    Console.WriteLine(error.Frames.Count);
}

The added line is 0.

The short answer

When a local script throws an Error that reaches your C# host, catch JsException and enumerate error.Frames. Read frame.Function (or check IsTopLevel), frame.Source.Name, and frame.Position. These are structured fields: you don’t have to split a formatted string on colons or infer which line is the innermost caller. For a string or number thrown instead of an Error, use error.Value if you need the thrown value; there are no captured frames on it.

How do you get a JavaScript stack trace when an exception is thrown?

For a C# host, JsException.Frames is the JavaScript call stack captured when the error object was created, innermost first. That timing matters: if a script creates an Error in one function and throws the same object in another, don’t expect the frames to move to the newer throw statement. In this example, construction and throw happen on the same line; the call to Error in fail is first, and the caller frames follow it.

The inherited Exception.StackTrace describes the .NET exception, not the script frames. JavaScript’s error.stack is useful as text, for example when you log a caught error in the script. In C#, use Frames when you want to present each function and source location as separate fields. The stack trace docs describe how stack text differs from report formatting, including how the text report can collapse repeated frames.

How do you get the line and column number of a JavaScript error?

Use frame.Position.Line and frame.Position.Column for each script frame. Both start at one. Columns count UTF-16 code units, not bytes or visual character cells. A character represented by a surrogate pair counts as two units. If you display the line in an editor, convert from that convention to the editor’s coordinate convention rather than assuming the reported column is a screen offset.

The stack location doesn’t necessarily point to the start of the statement. In throw new Error() it points to new; the next frame points to fail in function run() { fail(); }. A property access can point at the property name. Position uses the captured position when available, otherwise the start of Span; the span is the range used for the diagnostic underline. Use the location for a stack frame’s jump target and the span if you need the expression range. See the pinned position rules.

All oneecma recipes