Skip to main content

How to Return an Error from Action.Execute in the Microsoft 365 Agents SDK in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

When an Action.Execute button sends something your agent can't accept, answer with an error and a reason. The chat app shows the reason under the card, in red, and the person can fix their input and try again. In the Microsoft 365 Agents SDK, AdaptiveCardInvokeResponseFactory.BadRequest builds that answer.

Syntax​

C#
return AdaptiveCardInvokeResponseFactory.BadRequest(message);
  • BadRequest(message) builds an answer with statusCode 400, type application/vnd.microsoft.error, and a value with the code BadRequest and your message.
  • Return it from an Action.Execute handler, one you registered with AdaptiveCards.OnActionExecute.

The factory has other errors too: NotSupported(message), also 400; InternalError(message), a 500; and Error(statusCode, code, message) for your own. Microsoft's Universal Action model defines the 400: The incoming request was invalid.

The Example​

The agent for this post answers order with a sandwich order card: one number input, How many sandwiches?, and an Order button. The agent accepts 1 to 10. Anything else gets the error Order between 1 and 10 sandwiches., and an accepted order gets a short message. The agent is one class in an ASP.NET Core project with the Agents SDK, hosted with AddAgent<OrderAgent>() and listening on port 3978.

Prerequisites​

  • The Microsoft 365 Agents Playground, to chat with the agent on your own machine. agentsplayground --version should print 0.2.30; if the command isn't found, install it with npm install -g @microsoft/m365agentsplayground.

Step 1: Check What the Card Sent​

OrderAgent.cs
using System.Text.Json.Nodes;
using Microsoft.Agents.Builder;
using Microsoft.Agents.Builder.App;
using Microsoft.Agents.Builder.App.AdaptiveCards;
using Microsoft.Agents.Builder.State;
using Microsoft.Agents.Core.Models;
using Microsoft.Agents.Core.Serialization;

namespace SandwichOrder;

public class OrderAgent : AgentApplication
{
private const string OrderCardJson = """
{
"type": "AdaptiveCard",
"version": "1.5",
"body": [
{ "type": "TextBlock", "text": "Sandwich order", "size": "Large", "weight": "Bolder" },
{ "type": "Input.Number", "id": "count", "label": "How many sandwiches?" }
],
"actions": [
{ "type": "Action.Execute", "title": "Order", "verb": "order" }
]
}
""";

public OrderAgent(AgentApplicationOptions options) : base(options)
{
OnMessage("order", SendOrderCardAsync);
AdaptiveCards.OnActionExecute("order", OrderAsync);
}

private Task SendOrderCardAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
Attachment card = new() { ContentType = ContentTypes.AdaptiveCard, Content = JsonNode.Parse(OrderCardJson) };
return turnContext.SendActivityAsync(MessageFactory.Attachment(card), cancellationToken);
}

private Task<AdaptiveCardInvokeResponse> OrderAsync(ITurnContext turnContext, ITurnState turnState, object data, CancellationToken cancellationToken)
{
OrderData order = ProtocolJsonSerializer.ToObject<OrderData>(data);

// Card values arrive as text, so read the number yourself and say what's wrong.
if (!int.TryParse(order.Count, out int count) || count < 1 || count > 10)
{
return Task.FromResult(AdaptiveCardInvokeResponseFactory.BadRequest("Order between 1 and 10 sandwiches."));
}

return Task.FromResult(AdaptiveCardInvokeResponseFactory.Message($"Ordered {count} sandwiches."));
}
}

public record OrderData(string? Count);

OrderAgent.cs in a macOS-style editor window: the sandwich order card with a count Input.Number and an Order button, the order routes, and OrderAsync returning AdaptiveCardInvokeResponseFactory.BadRequest when the count isn't a number from 1 to 10, and a message otherwise

  • OrderData reads the input count from data. It's a string?, because the card sends every value as text, the number included, and leaves out an empty input.
  • int.TryParse turns the text into a number only if it is one. Together with the range check, that catches an empty input, a word, and a number out of range in one condition.
  • BadRequest answers with the reason. A message answers an order that went through.

The message OnMessage("order", ...) and the button's verb order don't clash: a typed message and an Action.Execute invoke are different activities, with different routes.

Step 2: Try It​

Run the agent with dotnet run, then start the Agents Playground in a second terminal, on its Teams channel:

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

In Personal Chat, send order, and type 12:

The Agents Playground: Test Bot's card Sandwich order, How many sandwiches?, with 12 in the number box and an Order button

Select Order:

The card with a red bar along its bottom: a warning icon, Order between 1 and 10 sandwiches., and a close button; the number box is empty again

The reason appears in a red bar with a warning icon. The Playground also emptied the number box. In the Log Panel, the invoke 200 entry shows what was sent and what came back:

The invoke's value (Request tab)
"value": {
"action": {
"type": "Action.Execute",
"title": "Order",
"verb": "order",
"data": {
"count": "12"
}
}
},
The agent's answer (Response tab)
{
"statusCode": 400,
"type": "application/vnd.microsoft.error",
"value": {
"code": "BadRequest",
"message": "Order between 1 and 10 sandwiches."
}
}
  • "count": "12": the number arrived as text, in quotes.
  • The log entry says invoke 200, but the answer's statusCode is 400. The HTTP response to the invoke is always 200 when the agent handled it; the error is inside the answer. Microsoft's Universal Action model: A client application MUST always look at the statucCode property in the response's body to know how the Bot processed the request.

Now type 3 and select Order again:

The card with a grey bar along its bottom: Ordered 3 sandwiches., and a close button

A valid order gets the message, in the grey bar of a normal answer.

Common Mistakes​

MistakeWhat happensDo this instead
Reading the number input into an int propertyThe value arrives as text, so it doesn't fit an intRead it into a string?, and parse it yourself
Relying on the card alone to check the inputAnother app, an old card or a hand-made request can still send anythingCheck every value in the handler too
Throwing an exception for bad inputThe person doesn't learn what to fixReturn BadRequest with the reason
A vague message such as Invalid inputThe person doesn't know what to changeSay what's accepted: Order between 1 and 10 sandwiches.

Troubleshooting​

SymptomLikely causeFix
The red bar shows for every orderThe input's id and the record's property don't match, so Count is always nullName the property after the input's id
The bar is grey for a bad orderThe handler returned MessageReturn BadRequest for errors
No bar at allNo route for the button's verbCompare the button's verb with the route's

FAQ​

Which status should I use?​

400, with BadRequest, when the request itself is wrong, such as bad input. 500, with InternalError, when your agent failed, such as a service it depends on being down. NotSupported is a 400 with its own code, for actions the agent doesn't support.

Does the error change the card?​

No. In this series' tests, in the Playground and in Microsoft Teams, the card's content stayed the same, with the error in a red bar under it. The Playground emptied the number box, as it empties a card's inputs after every action it sends.

Can I check inputs on the card itself?​

Yes: Adaptive Card inputs have isRequired, min, max and other properties that the chat app checks before sending. Keep the check in your handler too, because nothing forces a request to come from your card.

Conclusion​

To reject what an Action.Execute button sent, check the values in your handler and return AdaptiveCardInvokeResponseFactory.BadRequest with a reason the person can act on. Chat apps show it in red under the card, which stays as it was.

Additional Resources​