Sub topic 7
Returning Errors and Empty Results the Agent Can Explain
This chapter assumes you have written an @InvocableMethod with request and response wrapper classes, and that your method already handles a list of requests in one pass. You should also be comfortable with Database.update and its allOrNone flag. Here you will decide what your action returns when something goes wrong or when nothing is found.
Why the agent needs a message, not an exception
The agent decides what to tell the user from what your action returns. A sentence like "No open cases were found for this account" gives it something accurate to repeat. An uncaught exception gives it much less. The call fails, and the agent receives a generic failure instead of your wording. Because the platform passes your method a list, one uncaught exception also fails every request in that list, not only the bad one.
Your goal is to turn expected problems into ordinary return values. Reserve exceptions for situations you did not predict.
Three kinds of outcome
Each request ends in one of three states. The agent needs a different response for each.
| Outcome | Example | What to return |
|---|---|---|
| Success with data | Three open cases found | The data and a count |
| Success with nothing | The account has no open cases | A zero count and a sentence saying so |
| Failure | Missing input, no permission, a rejected DML row | `succeeded = false` and a plain sentence explaining why |
An empty result is not an error. If you return an empty string for "no cases", the agent cannot tell whether the lookup worked and found nothing, or whether it broke. The GetOpenCasesAction from earlier chapters handles this correctly. It sets caseCount to 0 and puts a message in summary.
Adding a status and a message to the response type
For actions that change data, add two fields to the response class:
- A Boolean, such as
succeeded, that states the outcome directly. - A String, such as
message, that carries a readable sentence for either outcome.
Give both fields clear descriptions. The agent reads them in the same way it reads input descriptions.
A complete example with per-request failures
This action changes the status of cases. It validates each request, runs one DML statement for all valid requests, and reports a separate result for each request in the original order.
public with sharing class UpdateCaseStatusAction {
public class Request {
@InvocableVariable(
label='Case Id'
description='The Salesforce Id of the case to update'
required=true
)
public Id caseId;
@InvocableVariable(
label='New Status'
description='The status to set, for example Working or Closed'
required=true
)
public String newStatus;
}
public class Response {
@InvocableVariable(
label='Succeeded'
description='True if the case was updated, false if nothing was changed'
)
public Boolean succeeded;
@InvocableVariable(
label='Result Message'
description='A plain sentence saying what happened or why the update did not happen'
)
public String message;
}
@InvocableMethod(
label='Update Case Status'
description='Changes the status of one case. Use only after the user has confirmed the new status'
category='Service'
)
public static List<Response> updateStatus(List<Request> requests) {
List<Response> responses = new List<Response>();
List<Case> toUpdate = new List<Case>();
List<Integer> updateIndexes = new List<Integer>();
Set<Id> seenIds = new Set<Id>();
for (Integer i = 0; i < requests.size(); i++) {
Request r = requests[i];
String problem = findProblem(r, seenIds);
if (problem != null) {
responses.add(buildResponse(false, problem));
continue;
}
seenIds.add(r.caseId);
responses.add(buildResponse(false, 'The update was not attempted.'));
toUpdate.add(new Case(Id = r.caseId, Status = r.newStatus.trim()));
updateIndexes.add(i);
}
if (toUpdate.isEmpty()) {
return responses;
}
try {
List<Database.SaveResult> results = Database.update(
toUpdate,
false,
AccessLevel.USER_MODE
);
for (Integer j = 0; j < results.size(); j++) {
Response res = responses[updateIndexes[j]];
if (results[j].isSuccess()) {
res.succeeded = true;
res.message = 'The case status was changed to ' + toUpdate[j].Status + '.';
} else {
res.message = 'The case was not updated: '
+ results[j].getErrors()[0].getMessage();
}
}
} catch (NoAccessException e) {
markAttempted(
responses,
updateIndexes,
'You do not have permission to update the status of cases.'
);
} catch (Exception e) {
System.debug(LoggingLevel.ERROR, e.getMessage() + '\n' + e.getStackTraceString());
markAttempted(
responses,
updateIndexes,
'The case could not be updated because of an unexpected problem.'
);
}
return responses;
}
private static String findProblem(Request r, Set<Id> seenIds) {
if (r.caseId == null) {
return 'No case was specified, so nothing was changed.';
}
if (r.caseId.getSObjectType() != Case.SObjectType) {
return 'The Id provided is not a case Id.';
}
if (String.isBlank(r.newStatus)) {
return 'No new status was provided.';
}
if (seenIds.contains(r.caseId)) {
return 'This case appears more than once in the same batch.';
}
return null;
}
private static Response buildResponse(Boolean succeeded, String message) {
Response res = new Response();
res.succeeded = succeeded;
res.message = message;
return res;
}
private static void markAttempted(
List<Response> responses,
List<Integer> indexes,
String message
) {
for (Integer idx : indexes) {
responses[idx].succeeded = false;
responses[idx].message = message;
}
}
}How the example handles each failure
- Validation first.
findProblemchecks the inputs before any DML. A null Id, an Id for a different object, a blank status, and a duplicate Id each get their own sentence. Duplicates matter because a DML list that contains the same Id twice would otherwise cause an error that affects the whole statement. - One response per request. The code adds a response for every request as it loops, so the output list always matches the input list in size and order. The agent platform relies on that ordering.
- Partial success. Passing
falseforallOrNonelets valid rows save even if another row is rejected. A rejected row, such as an invalid restricted picklist value, produces an error in itsSaveResult. The code copies that message into the matching response. - Two catch blocks. User-mode DML can report access problems either as row errors or as an exception, so the code handles both.
NoAccessExceptiongets a specific, safe sentence. The generalExceptionblock logs the details for developers and gives the agent a generic sentence.
Placeholder responses
Notice that each attempted request starts with the message "The update was not attempted." and succeeded = false. If a code path forgets to update a response, the agent will not see a null value or a false success. This is a small defensive habit that costs one line.
What a good message looks like
Write messages as if the user will read them, because the agent will often paraphrase them closely.
- Use full sentences in plain language. "No open cases were found for this account." works. "ERR_0" does not.
- Say what happened and, where useful, what to try. "No new status was provided." tells the agent to ask the user for one.
- Keep internals out. Do not return stack traces, class names, or SOQL text. Log them with
System.debugor your logging framework. - Do not reveal more than the user may see. A message that names a record the user cannot access defeats the sharing rules you set up earlier.
- Stay consistent. Use the same wording for the same failure so that the agent's explanations stay stable.
Decision flow for one request
Testing the failure paths
Failure paths need tests for the same reason success paths do. The test class below checks a bad status, a missing input, and a mixed batch where order must be preserved. It assumes the standard Case.Status values New and Working exist in the org.
@IsTest
private class UpdateCaseStatusActionTest {
private static UpdateCaseStatusAction.Request makeRequest(Id caseId, String status) {
UpdateCaseStatusAction.Request req = new UpdateCaseStatusAction.Request();
req.caseId = caseId;
req.newStatus = status;
return req;
}
@IsTest
static void rejectsStatusNotInPicklist() {
Case c = new Case(Subject = 'Test case', Status = 'New');
insert c;
List<UpdateCaseStatusAction.Response> results = UpdateCaseStatusAction.updateStatus(
new List<UpdateCaseStatusAction.Request>{ makeRequest(c.Id, 'Not A Real Status') }
);
Assert.areEqual(1, results.size());
Assert.isFalse(results[0].succeeded);
Assert.isTrue(results[0].message.startsWith('The case was not updated'));
}
@IsTest
static void keepsOrderInMixedBatch() {
Case c = new Case(Subject = 'Mixed batch', Status = 'New');
insert c;
List<UpdateCaseStatusAction.Response> results = UpdateCaseStatusAction.updateStatus(
new List<UpdateCaseStatusAction.Request>{
makeRequest(c.Id, 'Working'),
makeRequest(c.Id, null)
}
);
Assert.areEqual(2, results.size());
Assert.isTrue(results[0].succeeded);
Assert.isFalse(results[1].succeeded);
Assert.areEqual('No new status was provided.', results[1].message);
Assert.areEqual('Working', [SELECT Status FROM Case WHERE Id = :c.Id].Status);
}
@IsTest
static void reportsMissingCaseId() {
List<UpdateCaseStatusAction.Response> results = UpdateCaseStatusAction.updateStatus(
new List<UpdateCaseStatusAction.Request>{ makeRequest(null, 'Working') }
);
Assert.isFalse(results[0].succeeded);
Assert.areEqual('No case was specified, so nothing was changed.', results[0].message);
}
}In the mixed-batch test, the same Id appears twice, so the first request is valid and the second is rejected for its blank status before the duplicate check runs. The test shows that one bad request does not stop the good one, and that each response lines up with its request.
Common mistakes
- Throwing
AuraHandledExceptionor a custom exception for "no records found". This is an expected result, so return a message. - Returning an empty list from the method when no records match. The platform expects one response per request, so return a response for every request.
- Putting
e.getMessage()straight into the response for unexpected errors. It can expose field names, record Ids, or internal logic. - Leaving
messagenull on success. The agent may then give a vague confirmation, so always confirm what changed.
Exercise
Your action receives a list of five requests. Two have a blank required input, and three are valid. A teammate wants to throw an exception as soon as the first blank input is found. Explain what the agent would see, and describe what to do instead.
Show answer
A thrown exception is not caught, so the whole call fails. All five requests fail together, including the three valid ones, and the agent receives a generic failure instead of a sentence it can explain. Instead, validate each request, add a response with succeeded = false and a clear message such as "No new status was provided." for the two bad ones, and process the three valid ones normally. Return five responses in the same order as the five requests.
Exercise
A user asks the agent for the open cases on an account that has none. Which return value lets the agent answer correctly: an empty summary string with caseCount null, or caseCount = 0 with a message in summary? Why?
Show answer
Return caseCount = 0 with a message such as "No open cases were found for this account." An empty string with a null count is ambiguous. The agent cannot tell whether the lookup succeeded and found nothing or failed, so it may guess or report an error. A zero count plus an explicit sentence makes the empty result a clear, explainable answer.