Skip to main content

Fixed: The Microsoft 365 Agents SDK Sends the Exception Message to the User After OnTurnError

· 10 min read
Jagdish Kumawat
Founder @ Dewiride

My Microsoft 365 Agents SDK agent showed people the raw message of any exception it didn't catch, so I added an OnTurnError handler with a friendly message, the way Microsoft Learn shows it. After that, people got both: my message, and then the raw one. AgentApplication passes every exception on to the adapter's error handler after yours runs, and the fix is to replace that handler.

What I Was Doing​

I was building the bill-splitting agent for Part 3 of the Microsoft 365 Agents SDK Fundamentals, on Agents SDK 1.9.205 and .NET 10. Its route divides the bill by the number of people, so split 90 between 0 throws a DivideByZeroException. In the Microsoft 365 Agents Playground, the agent answered with the exception's message:

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

I didn't want users to see exception messages, so I added a turn error handler, as the Turn lifecycle hooks section of Learn's AgentApplication page shows: log the exception, then send a friendly message. I registered it in the agent's constructor:

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);

OnTurnError(TurnErrorAsync);
}

And added the handler:

BillSplitterAgent.cs (the turn error handler)
private async Task TurnErrorAsync(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);
}

Then I ran the agent and sent split 90 between 0 again.

What I Expected​

One reply: Sorry, I couldn't split that bill. Please try again.

What I Got​

Two replies, my message and then the exception's:

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

The Playground's Log Panel listed three activities from the agent, the last one a trace:

Agents Playground, Log Panel
[8:39:43 AM] Microsoft 365 Agents Playground -> User Application message 202 split 90 between 0
[8:39:43 AM] User Application -> Microsoft 365 Agents Playground message 201 Sorry, I couldn't split that bill. Please try again.
[8:39:43 AM] User Application -> Microsoft 365 Agents Playground message 201 Attempted to divide by zero.
[8:39:43 AM] User Application -> Microsoft 365 Agents Playground trace 202 OnTurnError Trace

What I Checked​

The agent's log. The exception was logged twice, first by my handler, then by the SDK's CloudAdapter:

Terminal (the agent)
fail: BillSplitter.BillSplitterAgent[0]
The bill splitter couldn't finish a turn.
System.DivideByZeroException: Attempted to divide by zero.
Terminal (the agent, a few lines later)
fail: Microsoft.Agents.Hosting.AspNetCore.CloudAdapter[0]
Unhandled exception during turn processing. Attempted to divide by zero.

So the exception didn't stop at my handler. After it ran, the exception reached the adapter as unhandled, and the adapter did exactly what it did before I added anything.

The API reference for AgentApplication.OnTurnError. Its remarks say it plainly: Exceptions here will bubble-up to Adapter.OnTurnError. They also warn that after-turn handlers and saving the turn state may not have happened.

The SDK's source, at version 1.9.205. AgentApplication.OnTurnAsync catches the exception, runs every turn error handler, and then throws it again:

AgentApplication.cs (Microsoft.Agents.Builder, excerpt)
catch (Exception ex)
{
onTurnTelemetryScope.Share(routeAuthorized, routeMatched);
foreach (AgentApplicationTurnError errorHandler in _turnErrorHandlers)
{
await errorHandler(turnContext, turnState, ex, cancellationToken).ConfigureAwait(false);
}
throw;
}

The adapter catches it next. The CloudAdapter's default error handler logs it, then sends the exception's message to the user as an ordinary message, and a trace activity with the details after it:

CloudAdapter.cs (Microsoft.Agents.Hosting.AspNetCore, excerpt)
await turnContext.SendActivityAsync(MessageFactory.Text(lastErrorMessage.ToString()), CancellationToken.None); // Includes only the exception messages.
await turnContext.TraceActivityAsync("OnTurnError Trace", resolvedErrorMessage, "https://www.botframework.com/schemas/error", "TurnError");

The SDK only delivers trace activities on the emulator channel, so in Microsoft Teams nobody sees the trace. The message has no such limit: it goes to every channel.

The API reference for ICloudAdapterErrorHandler. This interface exists for exactly this case: Register an implementation with dependency injection to replace the default OnTurnError handler without deriving from CloudAdapter. It adds that a replacement is responsible for both logging the exception and sending any desired response activities.

Why It Happens​

An agent has two error handlers in two layers. OnTurnError belongs to AgentApplication: it lets your agent react to an error, but it doesn't handle it in the sense of a catch block, because AgentApplication always throws the exception again afterwards. The second handler belongs to the adapter, and it runs for every exception that leaves a turn. Its default sends the exception's message to the user. So with OnTurnError alone, your message goes out, and then the default one goes out too.

The exception's message is written for developers. Depending on what failed, it can include a file path on your server, a server name, part of a database query or a value from someone's data, so it shouldn't reach users at all.

The Fix​

Replace the adapter's error handler with your own. 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.");
}
}
}
  • It logs every exception once, with its stack trace, because the default handler's logging goes away with it.
  • It stays quiet when turnContext.Responded is true, which means this turn has already sent something. My OnTurnError handler sends the friendly message, so after an error in a route, the user gets that message and nothing else.
  • It sends a generic message otherwise, for exceptions that never went through AgentApplication, such as one in middleware, where OnTurnError doesn't run.
  • It skips OperationCanceledException, as the default does: a cancelled turn has nobody to answer.

Register it in Program.cs. When the SDK creates the CloudAdapter, it looks for this service and uses it instead of its default handler:

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

Then take the logging out of the turn error handler, so each exception is logged once:

BillSplitterAgent.cs (the turn error handler)
private async Task TurnErrorAsync(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);
}

After the Fix​

I ran the agent again and sent split 90 between 0:

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

One message, and no trace activity in the Log Panel. The log has the exception once, from the new handler:

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)
at BillSplitter.BillSplitterAgent.SplitAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken) in /Users/you/source/BillSplitter/BillSplitterAgent.cs:line 33

Common Mistakes​

MistakeWhat happensDo this instead
Expecting OnTurnError to catch the exceptionAgentApplication throws it again, and the adapter's handler sends the raw messageReplace the adapter's handler with an ICloudAdapterErrorHandler
A replacement handler that always sends a messageUsers get two error messages when OnTurnError sends one tooCheck turnContext.Responded, or send from only one of the two
A replacement handler that doesn't logErrors disappear without a trace, because the default's logging went with itLog the exception in the replacement
Putting exception.Message in your own replyThe same leak, in your wordsSend a fixed message, and keep the details in the log

Troubleshooting​

SymptomLikely causeFix
The raw message still arrivesThe replacement isn't registered, or is registered under another typeRegister it as ICloudAdapterErrorHandler in Program.cs
No reply at all after an errorThe replacement returns early, or Responded was already true from an earlier reply in the same turnCheck the log for the fail: entry, and decide which handler should answer
The exception is logged twiceBoth OnTurnError and the replacement log itLog it only in the replacement

FAQ​

Can OnTurnError stop the exception from reaching the adapter?​

No. AgentApplication runs your turn error handlers and then throws the exception again, whatever they do. The only way to change what the adapter does with it is to replace the adapter's error handler.

Does this happen in Microsoft Teams too?​

The message, yes: the SDK sends it the same way on every channel. Only the trace activity is limited to the emulator channel, which is why you see it in the Agents Playground and Teams users don't.

Do I still need OnTurnError?​

Not for this fix. Keep it when your agent can say something more useful than a generic message, as the bill splitter does, or when it has to clean something up after an error. Otherwise the replacement handler alone covers every error.

Conclusion​

OnTurnError doesn't catch exceptions. AgentApplication runs your turn error handlers and passes the exception on to the CloudAdapter's error handler, whose default sends the exception's message to the user. Register your own ICloudAdapterErrorHandler that logs the exception and sends a message only when nobody has answered yet, and users see one message, written by you.

Additional Resources​