Sub topic 8
Reporting errors and using fault paths
This chapter assumes you can write an @InvocableMethod with request and result wrapper classes, and that you know why the method takes a list. It also assumes you can build a basic flow with Decision and Assignment elements. Here you will learn how a failure in Apex reaches the flow, and how to choose between throwing an exception and returning a failure in the result.
Two ways a method can fail
An invocable method can report a problem in two ways.
- Throw an exception. The call ends and the flow receives an error. If the Apex action has a fault connector, the flow follows it. If not, the flow fails.
- Return a failure. The method finishes normally and sets fields such as
isSuccessanderrorMessageon the result. The flow keeps going down the normal path, and a Decision element checks the result.
The two are not interchangeable. An exception applies to the whole call. A returned result applies to one input.
Flow batches work. A record-triggered flow that runs for 200 records can pass all 200 requests to your method in one call. Suppose 199 requests are fine and one is bad. If you throw, none of the 200 succeed and the flow cannot tell which input caused the problem. If you return a result per request, the 199 good ones proceed and the bad one is reported on its own.
Choosing between throwing and returning
| Situation | Better choice | Reason |
|---|---|---|
| One request has a missing or invalid value | Return a failed result | Other requests should still be processed |
| One record fails DML with `allOrNone` set to `false` | Return a failed result | `Database.SaveResult` gives you a per-record error |
| The method cannot do its job at all (a required setup record is missing, or the whole input is unusable) | Throw | No per-request result would be meaningful |
| An unexpected exception from a callout or query | Catch it, then throw a clear message, or convert it to failed results | The flow author gets a readable message |
A good default is to treat expected, data-related failures as results, and treat broken assumptions as exceptions.
Returning per-record results
The Result class from earlier chapters already carries isSuccess, taskId, and errorMessage. The part that goes wrong in practice is keeping results aligned with requests when you skip some of them.
Suppose you validate each request and only insert tasks for the valid ones. The list of SaveResult objects is then shorter than the list of requests. If you walk both lists with the same index, errors end up on the wrong interviews. The fix is to create one result per request up front, and remember which result each inserted task belongs to.
public with sharing class FollowUpTaskCreator {
public class Request {
@InvocableVariable(label='Account Id' required=true)
public Id accountId;
@InvocableVariable(label='Task Subject')
public String subject;
}
public class Result {
@InvocableVariable(label='Task Id')
public Id taskId;
@InvocableVariable(label='Is Success')
public Boolean isSuccess;
@InvocableVariable(label='Error Message')
public String errorMessage;
}
@InvocableMethod(
label='Create Validated Follow-up Tasks'
description='Creates one task per valid request. Failures are reported per request.'
)
public static List<Result> createTasks(List<Request> requests) {
List<Result> results = new List<Result>();
List<Task> tasksToInsert = new List<Task>();
List<Integer> resultIndexForTask = new List<Integer>();
for (Integer i = 0; i < requests.size(); i++) {
Request req = requests[i];
Result res = new Result();
res.isSuccess = false;
results.add(res);
if (req.accountId == null) {
res.errorMessage = 'An account Id is required.';
continue;
}
tasksToInsert.add(new Task(
WhatId = req.accountId,
Subject = String.isBlank(req.subject) ? 'Follow up' : req.subject,
ActivityDate = Date.today().addDays(7)
));
resultIndexForTask.add(i);
}
List<Database.SaveResult> saveResults = Database.insert(tasksToInsert, false);
for (Integer j = 0; j < saveResults.size(); j++) {
Result res = results[resultIndexForTask[j]];
if (saveResults[j].isSuccess()) {
res.isSuccess = true;
res.taskId = saveResults[j].getId();
} else {
res.errorMessage = saveResults[j].getErrors()[0].getMessage();
}
}
return results;
}
}Three details matter here:
resultsalways has exactly one entry per request, in request order. Flow depends on this.resultIndexForTaskis the map from an inserted task back to its result. Taskjbelongs to resultresultIndexForTask[j].Database.insert(tasksToInsert, false)allows partial success. With the defaultinsert tasks;, one bad row fails every row and throws aDmlException.
Initialize isSuccess to false rather than leaving it null. A null Boolean in a flow Decision can behave unexpectedly, and a result you forgot to fill in should look like a failure, not a success.
Throwing exceptions deliberately
Sometimes the right response is to stop. The next method throws when it can do no useful work, and it replaces a generic DML error with a message the flow author can act on.
public with sharing class AccountRenamer {
public class RenameException extends Exception {}
@InvocableMethod(label='Trim Account Names')
public static void trimNames(List<Id> accountIds) {
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
if (accounts.isEmpty()) {
throw new RenameException('No matching accounts were found.');
}
for (Account acc : accounts) {
acc.Name = acc.Name.trim();
}
try {
update accounts;
} catch (DmlException e) {
throw new RenameException('Could not update account names: ' + e.getDmlMessage(0));
}
}
}An exception thrown from an invocable method surfaces in the flow as a fault. The message you pass to the exception constructor is what the flow sees, so write it for the person building or debugging the flow. Do not leave it as a raw stack trace or an internal code.
Governor limit violations such as System.LimitException cannot be caught in Apex. A try/catch will not protect you from them. The way to deal with them is to bulkify the code so they never happen, as covered in the bulkification chapter.
Using the fault path in Flow Builder
In Flow Builder, an Apex action that can fail shows an option to add a Fault connector. You draw it from the action to another element. When the action throws an exception, the flow goes down that connector, not the normal one.
On the fault path you usually do one or more of these:
- Read the message. The global variable
{!$Flow.FaultMessage}contains the error text of the most recent fault. Copy it into a text variable with an Assignment element, because later faults overwrite it. - Tell the user. In a screen flow, send the user to a screen that displays the message in plain language.
- Log it. Use a Create Records element to write a record to a custom logging object, with the message and the flow name.
- Stop cleanly. End the flow, or use a Custom Error element in a record-triggered flow to block the save with a message you control.
Without a fault connector, the flow ends in an unhandled fault. In a screen flow the user sees a generic error. In a record-triggered flow, the user's save can fail, and an error email is typically sent to the flow's last modifier. Avoid depending on that for anything you care about.
For the returned-result approach, nothing special is needed in Flow. Add a Decision element after the action. One outcome checks whether the result's Is Success field equals {!$GlobalConstant.True}. The default outcome handles the failure and reads Error Message.
Each flow interview sees only its own Result, not the whole list. This is the payoff of aligned results: record 57's interview gets record 57's outcome.
Testing both kinds of failure
Test the returned failure and the thrown exception separately. For the exception, call the method inside try/catch, and call Assert.fail right after the call so the test fails if nothing is thrown. Assert.fail throws an AssertException, which a catch for your own exception type will not catch.
@IsTest
private class ErrorHandlingTest {
@IsTest
static void reportsFailuresPerRequestInOrder() {
Account acc = new Account(Name = 'Test Account');
insert acc;
FollowUpTaskCreator.Request good = new FollowUpTaskCreator.Request();
good.accountId = acc.Id;
FollowUpTaskCreator.Request missingId = new FollowUpTaskCreator.Request();
FollowUpTaskCreator.Request tooLong = new FollowUpTaskCreator.Request();
tooLong.accountId = acc.Id;
tooLong.subject = 'x'.repeat(256);
List<FollowUpTaskCreator.Result> results = FollowUpTaskCreator.createTasks(
new List<FollowUpTaskCreator.Request>{ good, missingId, tooLong }
);
Assert.areEqual(3, results.size(), 'One result per request');
Assert.isTrue(results[0].isSuccess, 'First request is valid');
Assert.isFalse(results[1].isSuccess, 'Second request has no account');
Assert.areEqual('An account Id is required.', results[1].errorMessage);
Assert.isFalse(results[2].isSuccess, 'Third subject exceeds 255 characters');
Assert.isNotNull(results[2].errorMessage);
}
@IsTest
static void throwsWhenNothingMatches() {
try {
AccountRenamer.trimNames(new List<Id>());
Assert.fail('Expected a RenameException');
} catch (AccountRenamer.RenameException e) {
Assert.areEqual('No matching accounts were found.', e.getMessage());
}
}
}The first test mixes a good request, a missing value, and a DML failure in one call. That checks the order of results, which is the most common source of bugs in this area.
Common mistakes
- Returning fewer results than requests. Flow cannot match results to interviews, and the call can fail with an error about the returned list size.
- Using the same index for two lists of different lengths. Keep an explicit index map, as in
resultIndexForTask. - Throwing for a single bad record. One bad record then fails the whole batch.
- Reading
$Flow.FaultMessagelate. Copy it into a variable immediately on the fault path. - Vague messages. Text like "Error occurred" gives the flow author nothing to act on. Say what failed and, where you can, which input.
Exercise
An invocable method receives 50 requests. Three have a blank required field. You want the other 47 to be processed and the three to be reported individually in the flow. Should you throw an exception for the blank values or return results? What must be true about the returned list?
Show answer
Return results. Throwing would fail the whole call and give the flow no way to identify the three bad requests. Return a list with exactly 50 results, in the same order as the requests, with isSuccess set to false and an errorMessage on the three invalid ones. The 47 valid requests are processed normally and get successful results.
Exercise
In the FollowUpTaskCreator code, 10 requests come in and request 4 has a null accountId. After validation, 9 tasks are inserted and the task at position 3 in tasksToInsert fails DML. Which entry in results receives that failure's error message, and why?
Show answer
The entry at index 4 of results is not it, since request 4 is the one skipped for validation. Task positions 0 to 3 map to requests 0 to 3, so the task at position 3 maps to request 3, and results[3] gets the DML error. Task position 4 maps to request 5, because resultIndexForTask records the original request index for each inserted task. Using the task position directly as the result index would put errors on the wrong requests after the skipped one.