Sub topic 7
Returning errors and empty results the agent can explain
This chapter assumes you can write an @InvocableMethod with request and response wrapper classes, as covered in earlier chapters, and that you know basic try/catch in Apex.
Why the agent needs readable results
The agent reads your response and turns it into a reply for the user. If the action throws an unhandled exception, the agent usually sees only a generic failure. It cannot tell the user what went wrong or what to try next. If the action returns an empty list or a blank field, the agent may guess, or say the action worked when it found nothing.
So treat every outcome as data the agent can read: success with results, success with nothing found, bad input, and a failure you can describe.
Return a message, don't throw
An invocable method receives a list of requests and must return a list of the same size, in the same order. One exception ends the whole batch. For expected problems, catch the exception and put a plain-language message in the response.
| Situation | What to return |
|---|---|
| Results found | `isSuccess = true`, count, and summary |
| Nothing found | `isSuccess = true`, count 0, and a summary that says so |
| Missing or invalid input | `isSuccess = false` and a message naming the input |
| Access or query failure | `isSuccess = false` and a safe message |
Keep stack traces, record Ids, and internal class names out of messages. Log them with System.debug instead.
Add status fields to the response
The action from earlier chapters gains two fields. isSuccess separates "found nothing" from "could not look". errorMessage carries the reason. Both have descriptions, because the agent reads them like any other output.
public with sharing class GetOpenCasesAction {
public class Request {
@InvocableVariable(
label='Account Id'
description='The Salesforce Id of the account whose open cases should be listed'
required=true
)
public Id accountId;
}
public class Response {
@InvocableVariable(
label='Succeeded'
description='True if the lookup ran. False if an error stopped it. True with zero cases means the account has no open cases'
)
public Boolean isSuccess;
@InvocableVariable(
label='Open Case Count'
description='Total number of open cases for the account'
)
public Integer caseCount;
@InvocableVariable(
label='Case Summary'
description='One line per case with case number and subject, or a message if there are none'
)
public String summary;
@InvocableVariable(
label='Error Message'
description='Plain-language reason the lookup failed. Empty when it succeeded'
)
public String errorMessage;
}
@InvocableMethod(
label='Get Open Cases'
description='Lists the open support cases for an account, newest first'
category='Service'
)
public static List<Response> getOpenCases(List<Request> requests) {
Set<Id> accountIds = new Set<Id>();
for (Request r : requests) {
if (r.accountId != null) {
accountIds.add(r.accountId);
}
}
Map<Id, List<Case>> casesByAccount = new Map<Id, List<Case>>();
try {
for (Case c : [
SELECT Id, CaseNumber, Subject, AccountId
FROM Case
WHERE AccountId IN :accountIds AND IsClosed = false
WITH USER_MODE
ORDER BY CreatedDate DESC
LIMIT 200
]) {
if (!casesByAccount.containsKey(c.AccountId)) {
casesByAccount.put(c.AccountId, new List<Case>());
}
casesByAccount.get(c.AccountId).add(c);
}
} catch (QueryException e) {
System.debug(LoggingLevel.ERROR, e.getMessage());
return failAll(
requests.size(),
'The current user cannot read cases, so the open cases could not be listed.'
);
}
List<Response> responses = new List<Response>();
for (Request r : requests) {
Response res = new Response();
if (r.accountId == null) {
res.isSuccess = false;
res.errorMessage = 'No account was provided. Ask the user which account to check.';
} else {
List<Case> cases = casesByAccount.containsKey(r.accountId)
? casesByAccount.get(r.accountId)
: new List<Case>();
res.isSuccess = true;
res.caseCount = cases.size();
res.summary = cases.isEmpty()
? 'No open cases were found for this account.'
: String.join(caseLines(cases), '\n');
}
responses.add(res);
}
return responses;
}
private static List<String> caseLines(List<Case> cases) {
List<String> lines = new List<String>();
for (Case c : cases) {
lines.add(c.CaseNumber + ': ' + c.Subject);
}
return lines;
}
private static List<Response> failAll(Integer count, String message) {
List<Response> responses = new List<Response>();
for (Integer i = 0; i < count; i++) {
Response res = new Response();
res.isSuccess = false;
res.errorMessage = message;
responses.add(res);
}
return responses;
}
}The query runs once, so a failure applies to every request. failAll still returns one response per request, which keeps the list sizes equal.
How the outcomes flow
Exercise
An account has no open cases. Should the action return isSuccess = false, and why or why not?
Show answer
No. The lookup ran correctly and found nothing, so isSuccess should be true with caseCount 0 and a summary saying no open cases were found. Reserving isSuccess = false for real failures lets the agent tell "nothing there" apart from "could not check".