Skip to main content

Part 3: Turn Events, Error Handling and Middleware

Routes decide which code answers an activity. Some code has to run for every activity, whichever route answers it: a log line, a check that can turn a request away, a safety net for when something breaks. In this part you add all three to a small bill-splitting agent, and you see exactly what your users get when an agent throws an exception. It's not what most people expect.

This is Part 3 of the Microsoft 365 Agents SDK Fundamentals, a 26-part series.

  1. Part 1: Activities and the Activity Protocol
  2. Part 2: Route Activities with AgentApplication
  3. Part 3: Turn Events, Error Handling and Middleware (you are here)
  4. Part 4: Conversation, User and Turn State
  5. Part 5: Send Adaptive Cards and Handle Their Actions
  6. Part 6: Send Proactive Messages (coming soon)
  7. Part 7: Stream Responses and Show Progress (coming soon)
  8. Part 8: Run Your Agent in Microsoft Teams (coming soon)
  9. Part 9: Universal Actions: Adaptive Cards That Update (coming soon)
  10. Part 10: Teams Dialogs (coming soon)
  11. Part 11: Commands, Suggested Actions and Targeted Messages (coming soon)
  12. Part 12: Mentions, Rosters and Team Events (coming soon)
  13. Part 13: Meeting Events (coming soon)
  14. Part 14: Send and Receive Files (coming soon)
  15. Part 15: Sign People In with SSO and OAuth (coming soon)
  16. Part 16: Message Extensions and Link Unfurling (coming soon)
  17. Part 17: AI Labels, Citations and Feedback (coming soon)
  18. Part 18: Bring Your Agent to Microsoft 365 Copilot (coming soon)
  19. Part 19: Store State in Azure Blob Storage and Cosmos DB (coming soon)
  20. Part 20: Telemetry with OpenTelemetry (coming soon)
  21. Part 21: Web Chat and Direct Line (coming soon)
  22. Part 22: Reach People in Slack (coming soon)
  23. Part 23: Call a Copilot Studio Agent (coming soon)
  24. Part 24: Agent-to-Agent Communication (coming soon)
  25. Part 25: Keep Conversation Transcripts (coming soon)
  26. Part 26: Deploy Your Agent to Azure (coming soon)

By the end of this part you'll know what runs before and after your routes on every turn, how to run your own code at those points and how to stop a turn early. You'll also know what happens to an exception your code doesn't catch, how to make sure people only ever see a message you wrote, and how middleware handles activities before your agent sees them. Every step works in VS Code and in Visual Studio; where they differ, the page shows a tab for each. Every output and screenshot on this page is real.

What Runs Around Every Turn​

A turn is everything your agent does with one activity: the SDK receives it, your code handles it, and the replies go out. Part 2's routes are the middle of a turn. Around them, the SDK runs code of its own and calls yours at fixed points, in this order:

  1. Middleware runs first. It lives in the adapter, the CloudAdapter that receives the HTTP request and sends your replies, so it sees the activity before your agent does, and it decides whether your agent sees it at all.
  2. AgentApplication loads the turn's state, the data it keeps between turns. Part 4 is about state.
  3. Your before-turn handlers run, in the order you registered them. Any of them can stop the turn here.
  4. The first route that matches runs, as in Part 2.
  5. Your after-turn handlers run.
  6. AgentApplication saves the state.
  7. Back in the middleware, the code after its call to the next step runs.

When a before-turn handler, a route or an after-turn handler throws an exception, AgentApplication runs your turn error handlers, and then passes the exception on to the adapter's own error handler, the last code that runs.

The Hooks at a Glance​

HookYou register it withIt runsUse it for
Middlewarebuilder.AddAgentMiddleware(...) in Program.csFor every activity, before and after your agentChecks and changes that don't belong to one agent
Before-turn handlerOnBeforeTurn(...) in your agentAfter the state loads, before the routesLogging and checks; return false to stop the turn
After-turn handlerOnAfterTurn(...)After the routes, before the state is savedLogging and follow-ups; return false to skip saving the state
Turn error handlerOnTurnError(...)When a before-turn handler, a route or an after-turn handler throwsTelling the user what went wrong, in your agent's words
Adapter error handlerAn ICloudAdapterErrorHandler serviceFor every exception that leaves the turnLogging the error, and a safe reply if nobody has answered

The last row matters more than it looks. The CloudAdapter comes with an error handler of its own, and by default it sends the exception's message to the user, as an ordinary message, in every channel, Microsoft Teams included. You'll watch it happen, and replace it.

The Example: A Bill Splitter​

To see each hook at work, you'll build a bill splitter. Send it split 90 between 3, and it answers That's 30.00 each. It has just two routes, one for split requests and a catch-all for everything else, so the hooks are the only new thing on the page. You'll add them one at a time:

StepYou addWhat you'll see
3A before-turn and an after-turn handler that log every turnEach turn's start and end in the terminal, around the route
4A before-turn handler that pauses the agentThe agent turning requests away while a setting is on
5Nothing: you split a bill between 0 peopleThe raw exception message, in the chat
6A turn error handlerA friendly message, and the raw one after it
7A replacement for the adapter's error handlerOnly the friendly message
8Middleware that limits how long a message can beLong messages answered before the agent sees them

The bill splitter has a bug on purpose: it doesn't check for zero people. That's what makes the error handling visible. You'll run it in the Microsoft 365 Agents Playground, as in Parts 1 and 2.

Prerequisites​

  • The .NET 10 SDK. dotnet --version should print 10.0. and a patch number; this page was built with 10.0.404.
  • The Microsoft 365 Agents Playground. agentsplayground --version should print 0.2.30. If the command isn't found, install it with npm install -g @microsoft/m365agentsplayground.
  • How routes work, from Part 2: Route Activities with AgentApplication.

Step 1: Create the Project​

Open a terminal in the folder where you keep your projects and create an empty ASP.NET Core project:

Terminal
dotnet new web -o BillSplitter
Output
The template "ASP.NET Core Empty" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/BillSplitter/BillSplitter.csproj:
Restore succeeded.

Then add the Agents SDK's hosting package, which brings the rest of the SDK with it:

Terminal
cd BillSplitter
dotnet add package Microsoft.Agents.Hosting.AspNetCore --version 1.9.205
Output (last lines)
info : PackageReference for package 'Microsoft.Agents.Hosting.AspNetCore' version '1.9.205' added to file '/Users/you/source/BillSplitter/BillSplitter.csproj'.
info : Generating MSBuild file /Users/you/source/BillSplitter/obj/BillSplitter.csproj.nuget.g.targets.
info : Writing assets file to disk. Path: /Users/you/source/BillSplitter/obj/project.assets.json
log : Restored /Users/you/source/BillSplitter/BillSplitter.csproj (in 3.26 sec).

Step 2: Write the Bill Splitter​

Create a file called BillSplitterAgent.cs in the project folder:

BillSplitterAgent.cs
using System.Globalization;
using System.Text.RegularExpressions;
using Microsoft.Agents.Builder;
using Microsoft.Agents.Builder.App;
using Microsoft.Agents.Builder.State;
using Microsoft.Agents.Core.Models;

namespace BillSplitter;

public class BillSplitterAgent : AgentApplication
{
private static readonly Regex SplitPattern = new(@"^split\s+(\d{1,7}(?:\.\d{1,2})?)\s+between\s+(\d{1,3})$", RegexOptions.IgnoreCase);

public BillSplitterAgent(AgentApplicationOptions options) : base(options)
{
OnMessage(SplitPattern, SplitAsync);
OnActivity(ActivityTypes.Message, HelpAsync, rank: RouteRank.Last);
}

private async Task SplitAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
Match match = SplitPattern.Match(turnContext.Activity.Text);
decimal amount = decimal.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
int people = int.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture);

decimal share = amount / people;

await turnContext.SendActivityAsync($"That's **{share:0.00}** each.", cancellationToken: cancellationToken);
}

private async Task HelpAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync("Send me a bill to split, such as **split 90 between 3**.", cancellationToken: cancellationToken);
}
}
  • SplitPattern matches split, an amount of up to seven digits with up to two decimals, between, and a number of people of up to three digits, ignoring case. The two groups in brackets capture the amount and the number of people.
  • decimal.Parse(..., CultureInfo.InvariantCulture) reads the amount the way the pattern wrote it, with a dot before the decimals. Without it, a computer set to a language that writes decimals with a comma would read 12.50 as 1250.
  • amount / people is the bug: (\d{1,3}) accepts 0, and dividing by zero throws an exception.
  • The catch-all with RouteRank.Last answers every other message, as in Part 2.

Replace everything in Program.cs with the same hosting Parts 1 and 2 use, with BillSplitterAgent as the agent:

Program.cs
using BillSplitter;
using Microsoft.Agents.Hosting.AspNetCore;
using Microsoft.Agents.Storage;

var builder = WebApplication.CreateBuilder(args);

builder.AddAgentDefaults()
.AddAgent<BillSplitterAgent>();
builder.Services.AddSingleton<IStorage, MemoryStorage>();

var app = builder.Build();

app.UseAgents();
app.MapDefaultAgentEndpoints();

app.Run();

Then open Properties/launchSettings.json and set the two applicationUrl lines to port 3978, where the Agents Playground looks by default:

Properties/launchSettings.json (the two lines to change)
"applicationUrl": "http://localhost:3978",
Properties/launchSettings.json (in the https profile)
"applicationUrl": "https://localhost:3979;http://localhost:3978",

Build it:

Terminal
dotnet build
Output
Restore complete (0.4s)
BillSplitter net10.0 succeeded (2.5s) → bin/Debug/net10.0/BillSplitter.dll

Build succeeded in 3.3s

And start it:

In the terminal, in the project folder:

Terminal
dotnet run
Output
Using launch settings from /Users/you/source/BillSplitter/Properties/launchSettings.json...
Building...
warn: Microsoft.Agents.Authentication.ConfigurationConnections[0]
No connections found in configuration.
warn: Microsoft.Agents.Authentication.ConfigurationConnections[0]
No connections map found in configuration.
info: Microsoft.Agents.Hosting.AspNetCore.BackgroundQueue.HostedActivityService[0]
Queued Hosted Service is running.
info: Microsoft.Agents.Hosting.AspNetCore.BackgroundQueue.HostedTaskService[0]
Queued Hosted Service is running.

info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:3978
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/you/source/BillSplitter

The two warnings mean the agent has no identity of its own yet, which the Playground doesn't need. Open a second terminal and start the Agents Playground as the emulator channel:

Terminal 2
agentsplayground -e http://localhost:3978/api/messages -c emulator

Send split 90 between 3, then hello:

The Agents Playground chat: split 90 between 3 gets That's 30.00 each. from Test Bot, with 30.00 in bold, and hello gets Send me a bill to split, such as split 90 between 3.

Both routes answer. Now for the code around them.

Step 3: Run Code Before and After Every Turn​

Stop the agent with Ctrl+C. Then give the agent a logger and register two turn handlers. The SDK creates a new instance of your agent class for every activity, through ASP.NET Core's dependency injection, so the constructor can ask for an ILogger<T> next to AgentApplicationOptions, like any class ASP.NET Core creates:

BillSplitterAgent.cs (the constructor)
private readonly ILogger<BillSplitterAgent> _logger;

public BillSplitterAgent(AgentApplicationOptions options, ILogger<BillSplitterAgent> logger) : base(options)
{
_logger = logger;

OnMessage(SplitPattern, SplitAsync);
OnActivity(ActivityTypes.Message, HelpAsync, rank: RouteRank.Last);

OnBeforeTurn(LogTurnStartAsync);
OnAfterTurn(LogTurnEndAsync);
}

Add the two handlers at the end of the class:

BillSplitterAgent.cs (the turn handlers)
private Task<bool> LogTurnStartAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
_logger.LogInformation("Turn started: {ActivityType}", turnContext.Activity.Type);
return Task.FromResult(true);
}

private Task<bool> LogTurnEndAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
_logger.LogInformation("Turn finished: {ActivityType}, answered: {Answered}", turnContext.Activity.Type, turnContext.Responded);
return Task.FromResult(true);
}
  • A turn handler has the same parameters as a route handler, but returns Task<bool>. true means carry on with the turn. These two do no asynchronous work, so they return Task.FromResult(true) instead of being async.
  • OnBeforeTurn and OnAfterTurn each take as many handlers as you register, and run them in that order.
  • turnContext.Responded is true once the agent has sent something in this turn.

Run the agent again with dotnet run. In the second terminal, stop the Playground with Ctrl+C and start it again with the same command, so it opens a new conversation, then send split 90 between 3. The agent's terminal shows two turns:

Terminal (the agent)
warn: Microsoft.Agents.Hosting.AspNetCore.CloudAdapter[4]
Anonymous access is enabled for channel: emulator.
info: BillSplitter.BillSplitterAgent[0]
Turn started: conversationUpdate
info: BillSplitter.BillSplitterAgent[0]
Turn finished: conversationUpdate, answered: False
warn: Microsoft.Agents.Hosting.AspNetCore.CloudAdapter[4]
Anonymous access is enabled for channel: emulator.
info: BillSplitter.BillSplitterAgent[0]
Turn started: message
info: System.Net.Http.HttpClient.Microsoft.Agents.Builder.RestChannelServiceClientFactory.LogicalHandler[100]
Start processing HTTP request POST http://localhost:56150/_connector/v3/conversations/2714eaf6-d148-4a9a-85d2-6dc0d5840391/activities/d9e3a961-4470-4764-b037-f7be42868345
info: System.Net.Http.HttpClient.Microsoft.Agents.Builder.RestChannelServiceClientFactory.ClientHandler[100]
Sending HTTP request POST http://localhost:56150/_connector/v3/conversations/2714eaf6-d148-4a9a-85d2-6dc0d5840391/activities/d9e3a961-4470-4764-b037-f7be42868345
info: System.Net.Http.HttpClient.Microsoft.Agents.Builder.RestChannelServiceClientFactory.ClientHandler[101]
Received HTTP response headers after 36.9167ms - 201
info: System.Net.Http.HttpClient.Microsoft.Agents.Builder.RestChannelServiceClientFactory.LogicalHandler[101]
End processing HTTP request after 49.425ms - 201
info: BillSplitter.BillSplitterAgent[0]
Turn finished: message, answered: True

The first turn is the conversationUpdate the Playground sends when it connects. No route takes it, so it ends with answered: False, but both handlers still ran: every activity gets a turn, and the turn handlers run for all of them. The second turn is your message. The four HttpClient lines between its start and its end are the route sending That's 30.00 each. to the Playground, so the order is exactly as promised: before-turn, route, after-turn.

The warning above each turn appears for every activity that arrives without authentication, which is how an agent with no identity of its own runs on your machine.

Step 4: Stop a Turn from OnBeforeTurn​

A before-turn handler that returns false stops the turn: no route runs, and neither do the after-turn handlers. You'll use that for a pause switch: a setting that makes the agent turn requests away, say while you fix something, without stopping the app.

Add the setting to appsettings.json, after "AllowedHosts":

appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"BillSplitter": {
"Paused": false
}
}

In BillSplitterAgent.cs, ask for IConfiguration in the constructor too, and register a second before-turn handler after the first:

BillSplitterAgent.cs (the constructor)
private readonly ILogger<BillSplitterAgent> _logger;
private readonly IConfiguration _configuration;

public BillSplitterAgent(AgentApplicationOptions options, ILogger<BillSplitterAgent> logger, IConfiguration configuration) : base(options)
{
_logger = logger;
_configuration = configuration;

OnMessage(SplitPattern, SplitAsync);
OnActivity(ActivityTypes.Message, HelpAsync, rank: RouteRank.Last);

OnBeforeTurn(LogTurnStartAsync);
OnBeforeTurn(StopWhenPausedAsync);
OnAfterTurn(LogTurnEndAsync);
}

Then add the handler, before LogTurnEndAsync:

BillSplitterAgent.cs (the pause switch)
private async Task<bool> StopWhenPausedAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
if (!_configuration.GetValue<bool>("BillSplitter:Paused"))
{
return true;
}

if (turnContext.Activity.Type == ActivityTypes.Message)
{
await turnContext.SendActivityAsync("The bill splitter is paused for maintenance. Please try again later.", cancellationToken: cancellationToken);
}

return false;
}
  • GetValue<bool>("BillSplitter:Paused") reads the setting on every turn. ASP.NET Core reloads appsettings.json when the file changes, so a running agent picks up a new value at its next turn.
  • Only messages get an answer while paused; any other activity is stopped quietly, since nobody is waiting for a reply.
  • The order matters. The logging handler is registered first, so even a paused turn is logged before the pause switch stops it.

When a before-turn handler stops a turn, the SDK still saves the turn's state, so your agent can remember why it stopped. Part 4 puts that state to use.

Start the agent again. While it runs, change "Paused": false to "Paused": true in appsettings.json, save the file, and send split 90 between 3 in the Playground. Then set it back to false, save, and send it once more:

The Playground chat: split 90 between 3 gets The bill splitter is paused for maintenance. Please try again later.; the same message sent again gets That's 30.00 each.

The first request was turned away while the switch was on, and the second went through, without restarting the agent. The terminal shows the difference:

Terminal (the agent, the paused turn)
info: BillSplitter.BillSplitterAgent[0]
Turn started: message
info: System.Net.Http.HttpClient.Microsoft.Agents.Builder.RestChannelServiceClientFactory.LogicalHandler[100]
Start processing HTTP request POST http://localhost:56150/_connector/v3/conversations/2714eaf6-d148-4a9a-85d2-6dc0d5840391/activities/520be7eb-bcbc-47f6-b95b-7649396d8258
info: System.Net.Http.HttpClient.Microsoft.Agents.Builder.RestChannelServiceClientFactory.ClientHandler[100]
Sending HTTP request POST http://localhost:56150/_connector/v3/conversations/2714eaf6-d148-4a9a-85d2-6dc0d5840391/activities/520be7eb-bcbc-47f6-b95b-7649396d8258
info: System.Net.Http.HttpClient.Microsoft.Agents.Builder.RestChannelServiceClientFactory.ClientHandler[101]
Received HTTP response headers after 74.3959ms - 201
info: System.Net.Http.HttpClient.Microsoft.Agents.Builder.RestChannelServiceClientFactory.LogicalHandler[101]
End processing HTTP request after 96.2811ms - 201

Turn started, the pause message going out, and then nothing: no route, and no Turn finished, because the after-turn handler never ran.

Step 5: See What Your Users Get When the Agent Fails​

Now trigger the bug. Send split 90 between 0:

The Playground chat: split 90 between 0 gets the reply Attempted to divide by zero. from Test Bot

Attempted to divide by zero. is the message of the DivideByZeroException that amount / people threw. Your code never caught it, so it left the turn, and the CloudAdapter's built-in error handler took it. That handler logged the exception, then sent its message to the user:

Terminal (the agent)
info: BillSplitter.BillSplitterAgent[0]
Turn started: message
fail: Microsoft.Agents.Hosting.AspNetCore.CloudAdapter[0]
Unhandled exception during turn processing. Attempted to divide by zero.
=====================================
ErrorCode: -2147352558
Source: System.Private.CoreLib
Method: VarDecDiv
TimeStamp: 2026-11-21T08:45:39.0353550Z
Error: Attempted to divide by zero.
HelpLink Url: Not Provided
=====================================

System.DivideByZeroException: Attempted to divide by zero.
at System.Decimal.DecCalc.VarDecDiv(DecCalc& d1, DecCalc& d2)
at System.Decimal.op_Division(Decimal d1, Decimal d2)

There's no Turn finished this time either: when a turn throws, the after-turn handlers don't run and the state isn't saved.

The Playground's Log Panel shows one more activity after the message: a trace called OnTurnError Trace, which carries the details the log has, such as the source and the method that failed. Trace activities are only delivered to the emulator channel, for developers; in Teams, nobody sees them. The message is different: it goes to every channel.

That's the problem. An exception's message is written for developers. Depending on what failed, it can contain a file path on your server, a server name, part of a database query or a value from someone's data, and the default handler shows it to whoever is chatting with your agent.

Step 6: Handle Errors with OnTurnError​

AgentApplication has its own error hook, OnTurnError, which runs when a before-turn handler, a route or an after-turn handler throws. Microsoft Learn's AgentApplication page shows it logging the exception and sending a friendly message, so start with that. Register it at the end of the constructor:

BillSplitterAgent.cs (the end of the constructor)
OnBeforeTurn(LogTurnStartAsync);
OnBeforeTurn(StopWhenPausedAsync);
OnAfterTurn(LogTurnEndAsync);
OnTurnError(HandleErrorAsync);
}

And add the handler at the end of the class:

BillSplitterAgent.cs (the turn error handler)
private async Task HandleErrorAsync(ITurnContext turnContext, ITurnState turnState, Exception exception, CancellationToken cancellationToken)
{
_logger.LogError(exception, "The bill splitter couldn't finish a turn.");
await turnContext.SendActivityAsync("Sorry, I couldn't split that bill. Please try again.", cancellationToken: cancellationToken);
}

A turn error handler gets the same three things a route handler does, plus the exception, and returns a plain Task. Run the agent again and send split 90 between 0:

The Playground chat: split 90 between 0 gets two replies: Sorry, I couldn't split that bill. Please try again., and then Attempted to divide by zero.

The friendly message arrived, and the raw one arrived right after it. The log shows why. Your handler logged the exception:

Terminal (the agent)
info: BillSplitter.BillSplitterAgent[0]
Turn started: message
fail: BillSplitter.BillSplitterAgent[0]
The bill splitter couldn't finish a turn.
System.DivideByZeroException: Attempted to divide by zero.
at System.Decimal.DecCalc.VarDecDiv(DecCalc& d1, DecCalc& d2)
at System.Decimal.op_Division(Decimal d1, Decimal d2)
at BillSplitter.BillSplitterAgent.SplitAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken) in /Users/you/source/BillSplitter/BillSplitterAgent.cs:line 37
at Microsoft.Agents.Builder.App.AgentApplication.OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)

Then, after the lines for your message going out, the CloudAdapter logged the same exception again, and sent its message as before:

Terminal (the agent, a few lines later)
fail: Microsoft.Agents.Hosting.AspNetCore.CloudAdapter[0]
Unhandled exception during turn processing. Attempted to divide by zero.

AgentApplication doesn't keep the exception after your handler runs. It runs your turn error handlers, then throws the exception again, and it reaches the adapter's error handler as if you'd done nothing. The API reference for OnTurnError says so in one line: Exceptions here will bubble-up to Adapter.OnTurnError. So OnTurnError alone can add a message, but it can't stop the raw one. I wrote this problem up on its own, with everything I checked: Fixed: The Microsoft 365 Agents SDK Sends the Exception Message to the User After OnTurnError.

Step 7: Replace the Adapter's Error Handler​

The fix is to replace the adapter's error handler. The SDK has an interface for exactly that, ICloudAdapterErrorHandler: register a class that implements it as a service, and the CloudAdapter uses it instead of its default. Create FriendlyErrorHandler.cs:

FriendlyErrorHandler.cs
using Microsoft.Agents.Builder;
using Microsoft.Agents.Hosting.AspNetCore;

namespace BillSplitter;

// Replaces the CloudAdapter's default error handler, which sends the exception's message to the user.
public class FriendlyErrorHandler(ILogger<FriendlyErrorHandler> logger) : ICloudAdapterErrorHandler
{
public async Task HandleTurnErrorAsync(ITurnContext turnContext, Exception exception)
{
logger.LogError(exception, "A {ActivityType} turn failed.", turnContext.Activity.Type);

// Say nothing when the turn was cancelled, or when the agent has already told the user.
if (exception is OperationCanceledException || turnContext.Responded)
{
return;
}

try
{
await turnContext.SendActivityAsync("Sorry, something went wrong. Please try again.", cancellationToken: CancellationToken.None);
}
catch (Exception sendException)
{
logger.LogWarning(sendException, "Couldn't tell the user that the turn failed.");
}
}
}
  • HandleTurnErrorAsync gets the turn and the exception. Microsoft's documentation for the interface says a replacement is responsible for both logging the exception and sending any desired response activities: the default's logging goes too, so this handler logs the exception itself, once, with its stack trace.
  • OperationCanceledException means the turn was cancelled, for example because the app is shutting down, so there's nobody to answer. The default handler skips those too.
  • turnContext.Responded is true when this turn has already sent something. Your OnTurnError handler sends the friendly message, so this handler stays quiet after it. An exception that never went through AgentApplication, such as one in middleware, never reached OnTurnError, so nothing was sent, and this handler answers with its own generic message.
  • The try block keeps a failure to send, such as a channel that can't be reached, from throwing out of the error handler. It's logged as a warning instead.

The class takes its logger through a primary constructor, the parameter list after the class name. The SDK creates the handler through dependency injection, so it can ask for services like any other class. Register it in Program.cs, below MemoryStorage:

Program.cs (the new line)
builder.Services.AddSingleton<ICloudAdapterErrorHandler, FriendlyErrorHandler>();

When the SDK creates the CloudAdapter, it looks for this service and, if there is one, uses it as the adapter's error handler. Where you register it in Program.cs doesn't matter.

Finally, take the logging out of HandleErrorAsync in BillSplitterAgent.cs, so each exception is logged once:

BillSplitterAgent.cs (the turn error handler)
private async Task HandleErrorAsync(ITurnContext turnContext, ITurnState turnState, Exception exception, CancellationToken cancellationToken)
{
// FriendlyErrorHandler logs the exception, so this handler only tells the user.
await turnContext.SendActivityAsync("Sorry, I couldn't split that bill. Please try again.", cancellationToken: cancellationToken);
}

Run the agent again and send split 90 between 0:

The Playground chat: split 90 between 0 gets a single reply, Sorry, I couldn't split that bill. Please try again.

One message, in your words. The log has the exception once, from FriendlyErrorHandler, after the lines for the friendly message going out:

Terminal (the agent)
fail: BillSplitter.FriendlyErrorHandler[0]
A message turn failed.
System.DivideByZeroException: Attempted to divide by zero.
at System.Decimal.DecCalc.VarDecDiv(DecCalc& d1, DecCalc& d2)
at System.Decimal.op_Division(Decimal d1, Decimal d2)

Your users see a message you wrote, and you still get the full exception, stack trace and all, in your log.

Step 8: Add Middleware​

Middleware handles activities before your agent does. A middleware is a class that implements the SDK's IMiddleware interface, and you'll write one that answers messages over a length limit itself, so they never reach the agent. A bill-splitting request is short; a 500-word paste is a mistake, and turning it away early costs nothing. Create MessageLengthLimitMiddleware.cs:

MessageLengthLimitMiddleware.cs
using Microsoft.Agents.Builder;
using Microsoft.Agents.Core.Models;
using IMiddleware = Microsoft.Agents.Builder.IMiddleware;

namespace BillSplitter;

// Answers messages that are too long itself, so they never reach the agent.
public class MessageLengthLimitMiddleware(int maxLength) : IMiddleware
{
public async Task OnTurnAsync(ITurnContext turnContext, NextDelegate next, CancellationToken cancellationToken = default)
{
if (turnContext.Activity.Type == ActivityTypes.Message && turnContext.Activity.Text?.Length > maxLength)
{
await turnContext.SendActivityAsync($"That message is too long. Please keep it to {maxLength} characters or fewer.", cancellationToken: cancellationToken);
return;
}

await next(cancellationToken);
}
}
  • OnTurnAsync is the one method of IMiddleware. It gets the turn, and next, the rest of the pipeline.
  • await next(cancellationToken) passes the activity on, to the next middleware or, after the last one, to your agent. Code you write after this line runs when the agent's whole turn has finished.
  • Returning without calling next ends the turn right there. The agent never sees the activity, and its state isn't even loaded.
  • maxLength comes in through the primary constructor, so each agent can set its own limit.
  • The using IMiddleware = ... line picks the Agents SDK's interface. ASP.NET Core has an IMiddleware interface too, and every web project imports its namespace automatically. Without this line the build fails with error CS0104: 'IMiddleware' is an ambiguous reference, which happened to me while building this page: Fixed: "error CS0104: 'IMiddleware' is an ambiguous reference between 'Microsoft.Agents.Builder.IMiddleware' and 'Microsoft.AspNetCore.Http.IMiddleware'".

Register the middleware in Program.cs, at the end of the AddAgentDefaults() chain:

Program.cs (the agent registration)
builder.AddAgentDefaults()
.AddAgent<BillSplitterAgent>()
.AddAgentMiddleware(new MessageLengthLimitMiddleware(maxLength: 100));

AddAgentMiddleware adds a middleware object to the adapter's pipeline. Call it once for each middleware; they run in the order you add them.

Run the agent again, paste a long message into the Playground, and then send a normal request:

The Playground chat: a 130-character message about a receipt with two pizzas, three drinks, a salad, a dessert and the tip gets That message is too long. Please keep it to 100 characters or fewer.; then split 120 between 4 gets That's 30.00 each.

The terminal shows who answered each one. For the long message, there's no Turn started: the middleware sent its reply, and the agent never ran. The bill request went through the agent as usual:

Terminal (the agent)
warn: Microsoft.Agents.Hosting.AspNetCore.CloudAdapter[4]
Anonymous access is enabled for channel: emulator.
info: System.Net.Http.HttpClient.Microsoft.Agents.Builder.RestChannelServiceClientFactory.LogicalHandler[100]
Start processing HTTP request POST http://localhost:56150/_connector/v3/conversations/2714eaf6-d148-4a9a-85d2-6dc0d5840391/activities/1df3ec5c-288a-49b3-a403-11d158e1c709
info: System.Net.Http.HttpClient.Microsoft.Agents.Builder.RestChannelServiceClientFactory.ClientHandler[100]
Sending HTTP request POST http://localhost:56150/_connector/v3/conversations/2714eaf6-d148-4a9a-85d2-6dc0d5840391/activities/1df3ec5c-288a-49b3-a403-11d158e1c709
info: System.Net.Http.HttpClient.Microsoft.Agents.Builder.RestChannelServiceClientFactory.ClientHandler[101]
Received HTTP response headers after 40.7685ms - 201
info: System.Net.Http.HttpClient.Microsoft.Agents.Builder.RestChannelServiceClientFactory.LogicalHandler[101]
End processing HTTP request after 55.0914ms - 201
warn: Microsoft.Agents.Hosting.AspNetCore.CloudAdapter[4]
Anonymous access is enabled for channel: emulator.
info: BillSplitter.BillSplitterAgent[0]
Turn started: message

That's the whole pipeline at work: the middleware first, then, for the activities it lets through, your turn handlers and routes inside AgentApplication.

The Complete Code​

Here is the finished agent:

BillSplitterAgent.cs
using System.Globalization;
using System.Text.RegularExpressions;
using Microsoft.Agents.Builder;
using Microsoft.Agents.Builder.App;
using Microsoft.Agents.Builder.State;
using Microsoft.Agents.Core.Models;

namespace BillSplitter;

public class BillSplitterAgent : AgentApplication
{
private static readonly Regex SplitPattern = new(@"^split\s+(\d{1,7}(?:\.\d{1,2})?)\s+between\s+(\d{1,3})$", RegexOptions.IgnoreCase);

private readonly ILogger<BillSplitterAgent> _logger;
private readonly IConfiguration _configuration;

public BillSplitterAgent(AgentApplicationOptions options, ILogger<BillSplitterAgent> logger, IConfiguration configuration) : base(options)
{
_logger = logger;
_configuration = configuration;

OnMessage(SplitPattern, SplitAsync);
OnActivity(ActivityTypes.Message, HelpAsync, rank: RouteRank.Last);

OnBeforeTurn(LogTurnStartAsync);
OnBeforeTurn(StopWhenPausedAsync);
OnAfterTurn(LogTurnEndAsync);
OnTurnError(HandleErrorAsync);
}

private async Task SplitAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
Match match = SplitPattern.Match(turnContext.Activity.Text);
decimal amount = decimal.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
int people = int.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture);

decimal share = amount / people;

await turnContext.SendActivityAsync($"That's **{share:0.00}** each.", cancellationToken: cancellationToken);
}

private async Task HelpAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync("Send me a bill to split, such as **split 90 between 3**.", cancellationToken: cancellationToken);
}

private Task<bool> LogTurnStartAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
_logger.LogInformation("Turn started: {ActivityType}", turnContext.Activity.Type);
return Task.FromResult(true);
}

private async Task<bool> StopWhenPausedAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
if (!_configuration.GetValue<bool>("BillSplitter:Paused"))
{
return true;
}

if (turnContext.Activity.Type == ActivityTypes.Message)
{
await turnContext.SendActivityAsync("The bill splitter is paused for maintenance. Please try again later.", cancellationToken: cancellationToken);
}

return false;
}

private Task<bool> LogTurnEndAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
_logger.LogInformation("Turn finished: {ActivityType}, answered: {Answered}", turnContext.Activity.Type, turnContext.Responded);
return Task.FromResult(true);
}

private async Task HandleErrorAsync(ITurnContext turnContext, ITurnState turnState, Exception exception, CancellationToken cancellationToken)
{
// FriendlyErrorHandler logs the exception, so this handler only tells the user.
await turnContext.SendActivityAsync("Sorry, I couldn't split that bill. Please try again.", cancellationToken: cancellationToken);
}
}

BillSplitterAgent.cs in a macOS-style editor window: an AgentApplication that takes AgentApplicationOptions, an ILogger and IConfiguration, and registers the split route, a catch-all ranked last, two OnBeforeTurn handlers, an OnAfterTurn handler and an OnTurnError handler

And Program.cs, with the error handler and the middleware registered:

Program.cs
using BillSplitter;
using Microsoft.Agents.Hosting.AspNetCore;
using Microsoft.Agents.Storage;

var builder = WebApplication.CreateBuilder(args);

builder.AddAgentDefaults()
.AddAgent<BillSplitterAgent>()
.AddAgentMiddleware(new MessageLengthLimitMiddleware(maxLength: 100));
builder.Services.AddSingleton<IStorage, MemoryStorage>();
builder.Services.AddSingleton<ICloudAdapterErrorHandler, FriendlyErrorHandler>();

var app = builder.Build();

app.UseAgents();
app.MapDefaultAgentEndpoints();

app.Run();

FriendlyErrorHandler.cs and MessageLengthLimitMiddleware.cs are as you wrote them in Steps 7 and 8, and appsettings.json is as in Step 4. The bug stays in on purpose, so you can watch the error handlers work. In your own agents, check input you can predict, such as zero people, and answer it in the route; the error handlers are for the failures you didn't predict.

Stop and Clean Up​

Press Ctrl+C in both terminals, or use Debug → Stop Debugging (Shift+F5) in Visual Studio. This part created nothing outside your project folder, and nothing in the cloud. The Playground wrote its log to a devTools folder in the folder you started it from; delete it whenever you like. When you've finished with the agent, delete the BillSplitter folder.

What You Can Do Now​

  • Name the order of a turn: middleware, state, before-turn handlers, the route, after-turn handlers, state again, and the error handlers when something throws.
  • Run your own code before and after every turn with OnBeforeTurn and OnAfterTurn, and stop a turn by returning false.
  • Change an agent's behavior while it runs with a setting in appsettings.json.
  • Explain why OnTurnError alone doesn't stop the raw exception message from reaching your users.
  • Replace the CloudAdapter's error handler with your own ICloudAdapterErrorHandler, so people only see messages you wrote.
  • Write middleware with IMiddleware, register it with AddAgentMiddleware, and stop activities before your agent sees them.

Common Mistakes​

MistakeWhat happensDo this instead
Relying on OnTurnError alone to hide exceptionsThe raw exception message still reaches the user, after yoursReplace the adapter's error handler with an ICloudAdapterErrorHandler
Sending a message from both error handlers, unconditionallyUsers get two error messagesSend from one, or check turnContext.Responded in the adapter's handler
Logging the exception in both error handlersEvery error is logged twiceLog it once, in the adapter's handler, which sees every error
A before-turn handler that forgets to return true on the normal pathEvery turn stops, and the agent never answersReturn true unless you mean to stop the turn
Counting on an after-turn handler after a failureIt doesn't run when the turn throwsPut clean-up that must always happen in the error handlers
Middleware that never calls nextYour agent never sees any activityCall await next(cancellationToken) on every path that should reach the agent
IMiddleware without the using alias in a web projecterror CS0104, an ambiguous referenceAdd using IMiddleware = Microsoft.Agents.Builder.IMiddleware;

Troubleshooting​

SymptomLikely causeFix
Users see Attempted to divide by zero. or another exception messageThe default adapter error handler is still in placeRegister your ICloudAdapterErrorHandler in Program.cs
Users get two error messagesBoth error handlers send a messageCheck turnContext.Responded before the adapter's handler answers
No Turn finished in the logA before-turn handler returned false, or the turn threwCheck the lines after Turn started for a reply or a fail: entry
The pause switch doesn't change anythingThe setting's name or section doesn't match, or the file wasn't savedUse exactly BillSplitter:Paused in the code and the same nesting in appsettings.json
The middleware never runsIt isn't registeredAdd .AddAgentMiddleware(...) in Program.cs
error CS0104: 'IMiddleware' is an ambiguous referenceASP.NET Core's IMiddleware is in scope tooAdd the using IMiddleware = ...; alias

FAQ​

Should OnTurnError or the adapter's error handler tell the user?​

Exactly one of them for each error. This part lets OnTurnError send the message, because it knows the agent and can say I couldn't split that bill, and makes the adapter's handler answer only when nothing was sent. If one generic message is enough for your agent, leave OnTurnError out and let the adapter's handler always answer.

What happens when middleware throws?​

OnTurnError doesn't run, because the exception never passed through AgentApplication. The adapter's error handler gets it directly. I checked this by making the middleware throw for one test message: no Turn started appeared, and FriendlyErrorHandler logged the exception and sent Sorry, something went wrong. Please try again. Errors while loading or saving state take the same path.

Should I use middleware or OnBeforeTurn?​

Use middleware for what doesn't belong to one agent and should happen before anything else, such as limits, filters and logging of every activity. It runs before the state is loaded, and you can reuse it in any agent. Use OnBeforeTurn for your agent's own checks, especially ones that need its turn state, which middleware doesn't have.

Can middleware use a logger or other services?​

AddAgentMiddleware takes an object you create yourself, so give the middleware what it needs through its constructor, as the SDK's own middleware does: ShowTypingMiddleware takes its timings, and TranscriptLoggerMiddleware takes the store it writes to.

Where do the typing indicator and mention removal happen?​

Inside AgentApplication, after the state loads and before your before-turn handlers. Both are options in the AgentApplication section of appsettings.json: StartTypingTimer, off by default, shows a typing indicator while your agent works, and Part 7 uses it. RemoveRecipientMention and NormalizeMentions, on by default, take your agent's @mention out of messages, which Part 12 shows in Teams.

Do I still need try and catch in my routes?​

For failures you can predict, yes: check the input, or catch the specific exception, and answer in the route, where you know what went wrong. The error handlers are the safety net for everything else.

Conclusion​

Every activity runs through the same pipeline: middleware in the adapter, then AgentApplication, which loads the state, runs your before-turn handlers, the first matching route and your after-turn handlers, and saves the state. A before-turn handler that returns false stops the turn. When something throws, your OnTurnError handlers run and the exception goes on to the adapter's error handler, whose default shows the exception's message to your users. Replace it with an ICloudAdapterErrorHandler, and people only ever see messages you wrote, while your log keeps every detail.

Next: Part 4: Conversation, User and Turn State. Your agent forgets everything between turns, because a new instance answers each activity. Part 4 gives it a memory, the state this part saw loaded and saved around every turn.

Additional Resources​