Sub topic 11
Returning errors and empty results clearly
This chapter covers what an action should return when something goes wrong or when nothing matches. It assumes you can read Apex and build a basic Flow, and that you know the agent reads the labels and descriptions you write. It builds on the earlier chapters on output design and on Apex and Flow implementation.
Why failure paths need design
When an action succeeds, the agent has data to explain. When it fails or finds nothing, the agent has only what you gave it. If the output is blank, the agent has to guess what that means. It may tell the customer the order does not exist when the real cause was a permissions problem. It may also retry the same call, or invent a plausible answer.
Your goal is to make each outcome distinguishable and to give the agent text it can safely relay. There are four outcomes to plan for:
| Outcome | Meaning | What the agent should do |
|---|---|---|
| Success | The action found and returned data | Explain the data |
| Empty result | The action ran correctly but nothing matched | Tell the user nothing was found, and offer to try other input |
| Invalid input | The value was malformed or out of range | Ask the user for a corrected value |
| Failure | Something broke, such as a missing permission or an unhandled error | Apologize, avoid guessing, and suggest another route |
Empty is not the same as failed
An empty result is a normal outcome. A customer typed an order number that does not exist. The query ran fine and returned zero rows. If your action returns nothing, the agent sees blank outputs and cannot tell this case from a broken action.
The fix is a dedicated message output that is always filled in. In the example from this tutorial, GetOrderStatus sets message in every branch, including the not-found branch:
Response res = new Response();
Order o = byNumber.get(r.orderNumber);
if (o == null) {
res.message = 'No order was found with number ' + r.orderNumber + '.';
} else {
res.status = o.Status;
res.message = 'Order ' + r.orderNumber + ' has status ' + o.Status + '.';
}The output descriptions tell the agent how to read each field. The Order Status description ends with "Empty if no order was found," and the Result Message description says it covers the case where no order matches. Together these tell the agent that an empty status paired with a message is a legitimate answer, not a fault.
Label: Order Status
Description: Current status of the order, such as Draft or Activated. Empty if no order was found.
Label: Result Message
Description: A short plain-language message describing the outcome, including when no order matches the number.Guidelines for the message output
- Fill it on every path. A message that is only set on errors forces the agent to infer success from its absence.
- Write it in plain language the user could read directly.
- Include the value that was searched, so the agent can confirm what it looked up. "No order was found with number 00000101" is better than "Not found."
- Keep it short. A long message adds tokens and gives the agent more room to paraphrase it badly.
- Do not include internal details such as record Ids, stack traces, or object API names unless the user needs them.
Adding a status field
A message works well for the agent to read. A separate machine-friendly field helps when topic instructions need to branch on the outcome. A short text output with a small set of values, such as Success, NotFound, InvalidInput, and Error, gives the instructions something exact to refer to.
public with sharing class GetOrderStatusV2 {
public class Request {
@InvocableVariable(
label='Order Number'
description='The order number the customer provided, for example 00000101. Ask the customer if it was not given. Do not guess.'
required=true
)
public String orderNumber;
}
public class Response {
@InvocableVariable(
label='Outcome'
description='One of Success, NotFound, InvalidInput, or Error. Success means the status field is filled in.'
)
public String outcome;
@InvocableVariable(
label='Order Status'
description='Current status of the order, such as Draft or Activated. Empty unless Outcome is Success.'
)
public String status;
@InvocableVariable(
label='Result Message'
description='A short plain-language message describing the outcome. Safe to relay to the customer.'
)
public String message;
}
@InvocableMethod(
label='Get Order Status'
description='Looks up the status of one order by its order number. Use when the customer asks where their order stands.'
)
public static List<Response> getStatus(List<Request> requests) {
List<Response> results = new List<Response>();
for (Request r : requests) {
results.add(lookUp(r));
}
return results;
}
private static Response lookUp(Request r) {
Response res = new Response();
if (String.isBlank(r.orderNumber) || !r.orderNumber.isNumeric()) {
res.outcome = 'InvalidInput';
res.message = 'The order number must contain digits only, for example 00000101.';
return res;
}
try {
List<Order> found = [
SELECT OrderNumber, Status
FROM Order
WHERE OrderNumber = :r.orderNumber
WITH USER_MODE
LIMIT 1
];
if (found.isEmpty()) {
res.outcome = 'NotFound';
res.message = 'No order was found with number ' + r.orderNumber + '.';
} else {
res.outcome = 'Success';
res.status = found[0].Status;
res.message = 'Order ' + r.orderNumber + ' has status ' + found[0].Status + '.';
}
} catch (Exception e) {
System.debug(LoggingLevel.ERROR, 'GetOrderStatus failed: ' + e.getMessage());
res.outcome = 'Error';
res.message = 'The order lookup is unavailable right now. Please try again later.';
}
return res;
}
}Several choices here matter:
- Validation happens before the query, and the invalid-input message tells the agent what a good value looks like. The agent can then ask the user again.
- The
catchblock logs the real error for administrators withSystem.debugand returns a generic message. The agent and the user never see the raw exception text. - Every branch sets both
outcomeandmessage. - The method returns one response per request, in the same order. An invocable method must return a list that lines up with its input list.
The query uses WITH USER_MODE, so a user who lacks access to orders gets an exception rather than silently filtered data. The catch block turns that exception into the Error outcome. Without the try block, the user would see a generic platform error and the agent would get no usable text.
Choosing between throwing and returning
An Apex action can end in two ways: it can return a response that describes the problem, or it can throw an unhandled exception. They behave differently for the agent.
| Approach | What the agent receives | Best for |
|---|---|---|
| Return an outcome and message | Text you wrote, as normal output | Expected problems: not found, bad input, a business rule refused |
| Throw an unhandled exception | A platform-level failure with little explanation | Rare, unexpected faults you cannot describe usefully |
Prefer returning for anything you can predict. Reserve a catch-all Error outcome for faults you did not predict, so those too produce a readable message instead of a platform failure.
Handling errors in Flow
A Flow action has the same needs. Add output variables for the outcome and the message, and mark both as available for output. Then use a fault path on each element that can fail, such as Get Records, Create Records, or Update Records.
- After a Get Records element, add a Decision that checks whether the record variable is null. On the null branch, assign
Outcome = NotFoundand setMessageto a plain sentence. - On the found branch, assign
Outcome = Success, fill the data outputs, and setMessage. - Connect a fault connector from each data element to an Assignment that sets
Outcome = Errorand a genericMessage. Record the real{!$Flow.FaultMessage}somewhere administrators can read it, such as a log record or a debug element, and do not copy it into the message output. - Make sure every path ends at the same finish point with the output variables assigned. An output variable that was never assigned on a path reaches the agent as empty.
Give each output variable a description with the same care as in Apex. The description on Outcome should list the possible values, because the agent reads it.
Telling the agent how to react
The action returns text, but the agent decides what to do next. Topic instructions are where you tie outcomes to behavior. Keep the instructions short and refer to the output names exactly:
After running Get Order Status:
- If Outcome is Success, tell the customer the status in one sentence.
- If Outcome is NotFound, say no order matched that number and ask them to check it. Do not try other numbers.
- If Outcome is InvalidInput, ask for the order number again using the format in the message.
- If Outcome is Error, apologize, say the lookup is unavailable, and offer to connect them with a person.The line "Do not try other numbers" is deliberate. Without it, an agent that gets a not-found result may try variations of the number on its own, which turns one failed lookup into several.
Common mistakes
- Blank outputs on failure. The agent cannot tell not-found from broken. Always fill the message.
- Success messages that hide errors. A message like "Done" on a path that failed makes the agent report success.
- One generic message for every failure. The agent cannot choose a different next step for bad input and a system fault. Use distinct outcomes.
- Leaking internals. Stack traces and field names confuse users and may expose data.
- Messages that give commands. A message such as "Tell the user to call support" mixes data with instructions. Put behavior in topic instructions and keep the message descriptive.
- Unassigned Flow outputs. A path that skips the assignment returns nothing, even if the logic seemed to cover it.
Testing the failure paths
Test each outcome on purpose, and do it in the agent as well as in the action in isolation. The action may be correct while the agent still misreads it.
- Run the action directly with a valid value, a nonexistent value, a malformed value, and a user who lacks access. Confirm each returns the expected outcome and message.
- In the agent's preview, ask a question that triggers each case and review the action inputs and outputs the agent used.
- Check that the agent's final reply matches the message and does not add facts that the action did not return.
- Check that the agent does not retry after a not-found or error result unless your instructions allow it.
- If the agent misreads an outcome, change the output description or the instruction wording first, and test again.
Summary of practices
- Treat empty, invalid, and failed as three separate outcomes from success.
- Always fill a plain-language message output, and describe it in the output description.
- Add a small outcome field when topic instructions need to branch.
- Catch predictable problems and return them as data. Log the real error elsewhere.
- Keep internal details out of anything the agent can repeat.
- Test every outcome through the agent, not only through the action.
Exercise
A Flow action looks up a case by case number. When no case matches, the Get Records element returns nothing, and the Flow finishes with all output variables unassigned. The agent tells users, "I couldn't check that right now." What is wrong, and what would you change?
Show answer
The action returns blank outputs for a normal not-found result, so the agent cannot distinguish it from a failure and falls back to a vague apology. Add a Decision after Get Records that checks for a null record. On the null branch, set an Outcome variable to NotFound and a Message variable such as "No case was found with number X." Set Outcome to Success and fill Message on the found branch. Add a fault connector that sets Outcome to Error with a generic message. Describe the output variables so the agent knows Outcome values and that an empty case status with a NotFound outcome is a valid answer.
Exercise
Why should the catch block in the Apex example return a generic message instead of e.getMessage()?
Show answer
Exception text can contain object names, field names, or record data. The agent may repeat it to the user word for word. Log the real message for administrators with System.debug or a log record, and return a safe, generic message in the response.