Skip to main content

How to Handle a Failed Step in a Microsoft Agent Framework Workflow in C#

· 9 min read
Jagdish Kumawat
Founder @ Dewiride

When a step in a Microsoft Agent Framework workflow throws an exception, InProcessExecution.RunAsync doesn't throw it to your code: the run reports the failure as events and ends. This guide runs a two-step workflow with a number and with text, and reads the failure from the events and from the run's status.

Syntax​

Syntax
await using Run <run> = await InProcessExecution.RunAsync(<workflow>, <input>);

foreach (WorkflowEvent <workflowEvent> in <run>.OutgoingEvents)
{
switch (<workflowEvent>)
{
case ExecutorFailedEvent <failed>:
// <failed>.ExecutorId is the step that failed, <failed>.Data its exception
break;
case WorkflowErrorEvent <error>:
// <error>.Exception is the error the workflow reports
break;
}
}

RunStatus <status> = await <run>.GetStatusAsync();
PartWhat it is
<workflow>, <input>The workflow to run, and the value its first step receives
OutgoingEventsEvery event the run emitted
ExecutorFailedEventRaised when a step's handler fails. ExecutorId names the step, and Data holds the exception
WorkflowErrorEventRaised when the workflow encounters an error. Exception holds it, if there is one
GetStatusAsync()Returns the run's status, a RunStatus value

Microsoft's guide to workflow events describes the two failure events in four words each: ExecutorFailedEvent is Executor encounters an error, and WorkflowErrorEvent is Workflow encounters an error. Agent Framework 1.28's documentation adds that an ExecutorFailedEvent's exception may be null if no exception was thrown.

The status says how the run stopped. These two values appear in this guide:

StatusMeaning, from Agent Framework 1.28's documentation
IdleThe run has halted and has no outstanding requests
EndedNo further events will be emitted, and no messages can be sent to it.

The others are PendingRequests, a run halted with at least one outstanding request, Running, and NotStarted, which only happens in lockstep mode.

The Example​

A console app called NumberDoubler has a workflow with two steps: ParseNumber turns text into a number with int.Parse, and DoubleNumber doubles it. The app runs the workflow twice, with "21" and with "abc", which isn't a number, and prints the output, any failure and the run's status each time. There's no AI model in it, so nothing needs an Azure account.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0; this guide used 10.0.404.

Step 1: Create a Console App​

In a terminal, in the folder where you keep your projects, create a console app, move into it and add Agent Framework's workflows package:

Terminal
dotnet new console -o NumberDoubler
cd NumberDoubler
dotnet add package Microsoft.Agents.AI.Workflows --version 1.28.0
  • dotnet new console -o NumberDoubler creates a console app in a new NumberDoubler folder, and cd moves into it.
  • dotnet add package adds Microsoft.Agents.AI.Workflows, Agent Framework's workflows package. --version keeps you on the version this guide used.
Output (shortened)
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/NumberDoubler/NumberDoubler.csproj:
Restore succeeded.
…
info : PackageReference for package 'Microsoft.Agents.AI.Workflows' version '1.28.0' added to file '/Users/you/source/NumberDoubler/NumberDoubler.csproj'.
info : Generating MSBuild file /Users/you/source/NumberDoubler/obj/NumberDoubler.csproj.nuget.g.targets.
info : Writing assets file to disk. Path: /Users/you/source/NumberDoubler/obj/project.assets.json
log : Restored /Users/you/source/NumberDoubler/NumberDoubler.csproj (in 1.46 sec).

This workflow's steps are plain functions, so the project needs only this package: the source generator package is for class-based executors.

Step 2: Build a Two-Step Workflow​

Replace everything in Program.cs with:

Program.cs
using Microsoft.Agents.AI.Workflows;

Func<string, int> parse = text => int.Parse(text);
Func<int, int> twice = number => number * 2;

ExecutorBinding parseNumber = parse.BindAsExecutor("ParseNumber");
ExecutorBinding doubleNumber = twice.BindAsExecutor("DoubleNumber");

Workflow workflow = new WorkflowBuilder(parseNumber)
.AddEdge(parseNumber, doubleNumber)
.WithOutputFrom(doubleNumber)
.Build();
  • parse turns text into a number with int.Parse, which throws for text that isn't a number. twice doubles a number.
  • BindAsExecutor("ParseNumber") turns a function into an executor, a step of the workflow, with the id in quotes.
  • AddEdge(parseNumber, doubleNumber) sends what ParseNumber returns to DoubleNumber, and WithOutputFrom(doubleNumber) makes the result of DoubleNumber the workflow's output.

Step 3: Run the Workflow and Read the Failure Events​

Add this below the workflow:

Program.cs (below the workflow)
foreach (string input in new[] { "21", "abc" })
{
Console.WriteLine($"Input: {input}");

// RunAsync doesn't throw when a step fails: the run reports it as events instead.
await using Run run = await InProcessExecution.RunAsync(workflow, input);

foreach (WorkflowEvent workflowEvent in run.OutgoingEvents)
{
switch (workflowEvent)
{
case WorkflowOutputEvent output:
Console.WriteLine($" Output: {output.Data}");
break;
case ExecutorFailedEvent failed:
Console.WriteLine($" {failed.ExecutorId} failed: {failed.Data?.GetType().Name}: {failed.Data?.Message}");
break;
case WorkflowErrorEvent error:
Console.WriteLine($" The run failed: {error.Exception?.GetType().Name}: {error.Exception?.Message}");
break;
}
}

Console.WriteLine($" Status: {await run.GetStatusAsync()}");
}
  • The outer loop runs the workflow once for each input.
  • InProcessExecution.RunAsync runs the workflow and hands back a Run. Its documentation: The workflow will run until its first halt, and the returned Run will capture all outgoing events. There's no try/catch around it, for the reason in the comment.
  • OutgoingEvents holds every event the run emitted, and the switch picks out three kinds. A WorkflowOutputEvent carries the output in Data. An ExecutorFailedEvent carries the failed step's id in ExecutorId and its exception in Data, and ?. guards against that exception being null. A WorkflowErrorEvent carries the workflow's error in Exception.
  • GetStatusAsync() reads the run's status after the events.

Step 4: Run the App​

Terminal
dotnet run
Output
Input: 21
Output: 42
Status: Idle
Input: abc
ParseNumber failed: FormatException: The input string 'abc' was not in a correct format.
The run failed: TargetInvocationException: Error invoking handler for System.String
Status: Ended

macOS-style terminal window titled Terminal — NumberDoubler showing dotnet run: input 21 gives Output: 42 and Status: Idle, while input abc gives ParseNumber failed: FormatException: The input string 'abc' was not in a correct format., then The run failed: TargetInvocationException: Error invoking handler for System.String, and Status: Ended

Line by line:

  1. 21 went through both steps: the output is 42, and the status is Idle, a run that halted with no outstanding requests.
  2. abc made ParseNumber fail. The ExecutorFailedEvent names the step and carries its own exception: a FormatException with the message from int.Parse.
  3. The WorkflowErrorEvent came next, with a TargetInvocationException. Its message, Error invoking handler for System.String, names the type of message the failed handler takes, a string, not the step.
  4. There's no Output line, and the status is Ended: this run emits nothing more and takes no more messages.

The program also ran to its end without an unhandled exception. RunAsync returned normally for abc too, and the loop went on to print the status.

What Each Event Tells You​

What you needWhere it isIn the example
Which step failedExecutorFailedEvent.ExecutorIdParseNumber
Why it failedExecutorFailedEvent.DataFormatException: The input string 'abc' was not in a correct format.
That the run failedA WorkflowErrorEventTargetInvocationException: Error invoking handler for System.String
Whether the run can go onGetStatusAsync()Ended
The result, when there is oneWorkflowOutputEvent.Data42

Log the ExecutorFailedEvent: it's the one with the step and the real exception. The WorkflowErrorEvent tells you the run failed, but its message only names a type.

The Complete File​

Program.cs
using Microsoft.Agents.AI.Workflows;

Func<string, int> parse = text => int.Parse(text);
Func<int, int> twice = number => number * 2;

ExecutorBinding parseNumber = parse.BindAsExecutor("ParseNumber");
ExecutorBinding doubleNumber = twice.BindAsExecutor("DoubleNumber");

Workflow workflow = new WorkflowBuilder(parseNumber)
.AddEdge(parseNumber, doubleNumber)
.WithOutputFrom(doubleNumber)
.Build();

foreach (string input in new[] { "21", "abc" })
{
Console.WriteLine($"Input: {input}");

// RunAsync doesn't throw when a step fails: the run reports it as events instead.
await using Run run = await InProcessExecution.RunAsync(workflow, input);

foreach (WorkflowEvent workflowEvent in run.OutgoingEvents)
{
switch (workflowEvent)
{
case WorkflowOutputEvent output:
Console.WriteLine($" Output: {output.Data}");
break;
case ExecutorFailedEvent failed:
Console.WriteLine($" {failed.ExecutorId} failed: {failed.Data?.GetType().Name}: {failed.Data?.Message}");
break;
case WorkflowErrorEvent error:
Console.WriteLine($" The run failed: {error.Exception?.GetType().Name}: {error.Exception?.Message}");
break;
}
}

Console.WriteLine($" Status: {await run.GetStatusAsync()}");
}

macOS-style code window titled Program.cs — NumberDoubler showing two functions bound as the executors ParseNumber and DoubleNumber, a workflow with an edge between them, and a loop that runs it with 21 and abc, prints the output, the ExecutorFailedEvent and the WorkflowErrorEvent, then the status from GetStatusAsync

Common Mistakes​

MistakeWhat happensDo this instead
Wrapping RunAsync in try/catch to catch a failed stepNothing is caught: the step's exception arrives as eventsLook for ExecutorFailedEvent and WorkflowErrorEvent in the run's events
Looking only for WorkflowOutputEventA failed run looks like a run that produced nothingHandle the two failure events too
Logging only the WorkflowErrorEventThe log says Error invoking handler for System.String, without the step or the real exceptionLog the ExecutorFailedEvent's ExecutorId and Data
Reading Data.Message without ?.The documentation says Data may be nullUse ?., as the example does

FAQ​

Can starting a run still throw an exception?​

Yes, for problems with the run itself rather than with one of its steps. For example, starting a second run on a workflow that another run still owns throws InvalidOperationException, as this fixes post shows. Keep a try/catch for those, and read the events for failed steps.

Can I see every event, not only the failures?​

Yes. Print each event in the loop, whatever its type. The guide to seeing every event in a workflow run does that, after the run and while it runs.

Conclusion​

A failed step doesn't make InProcessExecution.RunAsync throw. The run reports an ExecutorFailedEvent, with the step's id and its own exception, then a WorkflowErrorEvent, and its status becomes Ended. In the example, 21 gave 42 with the status Idle, and abc gave ParseNumber failed: FormatException with the status Ended. Read the events after every run, and log the step's own exception.

Additional Resources​

  • Events — the built-in workflow events, including the two failure events.
  • ExecutorFailedEvent — the event's ExecutorId and Data properties in the API reference.
  • Workflow Execution Modes — how RunAsync runs a workflow and collects its events.