Sub topic 15
Handling duplicate errors and bypassing rules in DML
This chapter covers what happens when Apex code or an API client saves a record that an active duplicate rule flags. It assumes you know how duplicate rules and their actions (block, alert, report) work from earlier chapters. It also assumes you can read basic Apex, including Database.insert and Database.SaveResult.
Duplicate rules also run on code-driven saves
Duplicate rules are not limited to the user interface. They run on Apex DML, on the SOAP and REST APIs, and on tools that use those APIs. A rule that only alerts a user in the UI still stops a save from code, because code cannot click "Save" on an alert.
The outcome depends on the rule's action and on the DML options you pass:
| Rule action | Default DML behavior | With `allowSave = true` |
|---|---|---|
| Block | Save fails with a duplicate error | Save still fails |
| Allow with alert | Save fails with a duplicate error | Save succeeds |
| Allow without alert | Save succeeds | Save succeeds |
| Report | Save succeeds, and a duplicate record set may be created | Same as default |
The key point is the second row. An alert rule is not a warning for code. It is an error until the caller acknowledges it.
Reading the duplicate error
With Database.insert(record, false), a blocked save does not throw. The failure appears in the SaveResult, and one of the errors is a Database.DuplicateError. If you use the plain insert statement or pass true for allOrNone, Apex throws a DmlException instead. Its status code is StatusCode.DUPLICATES_DETECTED.
Account acct = new Account(Name = 'Acme Corporation', BillingCity = 'Chicago');
Database.SaveResult saveResult = Database.insert(acct, false);
if (!saveResult.isSuccess()) {
for (Database.Error err : saveResult.getErrors()) {
if (err instanceof Database.DuplicateError) {
Database.DuplicateError dupError = (Database.DuplicateError) err;
Datacloud.DuplicateResult dupResult = dupError.getDuplicateResult();
System.debug('Blocked by rule: ' + dupResult.getDuplicateRule());
System.debug('Message: ' + dupResult.getErrorMessage());
System.debug('Can be saved anyway: ' + dupResult.isAllowSave());
}
}
}Datacloud.DuplicateResult carries the information you need to react:
getDuplicateRule()returns the developer name of the rule that fired.getErrorMessage()returns the message configured on the rule.isAllowSave()istruefor alert rules andfalsefor block rules. Use it to decide whether a retry withallowSavecan work.getMatchResults()returns the matching rules and the records they found, the same structure thatDatacloud.FindDuplicatesreturns.
Getting the matched records
By default, the match records contain little detail, mostly record IDs. To get field values for the matches, set includeRecordDetails on the DML options before the save. Without it, a handler that wants to show the user "this looks like Acme Corp in Chicago" has to query the IDs again.
Handling many records at once
In a bulk call such as Database.insert(list, false), each record gets its own SaveResult. Loop over the results and the input list by index. Do not assume that one duplicate error means the whole batch failed. Records that did not match any rule are saved.
Allowing a save when the rule is an alert
Setting allowSave on the DML options tells Salesforce that the caller has seen the alert and wants to proceed.
Account acct = new Account(Name = 'Acme Corporation', BillingCity = 'Chicago');
Database.DMLOptions dmlOptions = new Database.DMLOptions();
dmlOptions.DuplicateRuleHeader.allowSave = true;
dmlOptions.DuplicateRuleHeader.includeRecordDetails = true;
Database.SaveResult saveResult = Database.insert(acct, dmlOptions);
System.debug('Saved despite alerts: ' + saveResult.isSuccess());Two behaviors are easy to miss:
allowSaveonly overrides alerts. A rule whose action is Block still fails the save, andisSuccess()isfalse.- When the save succeeds despite a match, the record is still a duplicate. If the rule also has the report option, Salesforce records the match in a duplicate record set, which an administrator can review later.
A common two-step pattern
A typical integration or custom screen first saves normally. If it gets a DuplicateError where isAllowSave() is true, it shows the matches to the user. If the user confirms, it saves again with allowSave = true.
public with sharing class AccountSaver {
public class SaveOutcome {
public Boolean saved;
public Boolean needsConfirmation;
public List<Datacloud.MatchRecord> matches = new List<Datacloud.MatchRecord>();
}
public static SaveOutcome save(Account acct, Boolean userConfirmed) {
Database.DMLOptions opts = new Database.DMLOptions();
opts.DuplicateRuleHeader.allowSave = userConfirmed;
opts.DuplicateRuleHeader.includeRecordDetails = true;
Database.SaveResult sr = Database.insert(acct, opts);
SaveOutcome outcome = new SaveOutcome();
outcome.saved = sr.isSuccess();
outcome.needsConfirmation = false;
if (!sr.isSuccess()) {
for (Database.Error err : sr.getErrors()) {
if (err instanceof Database.DuplicateError) {
Datacloud.DuplicateResult dr =
((Database.DuplicateError) err).getDuplicateResult();
outcome.needsConfirmation = dr.isAllowSave();
for (Datacloud.MatchResult mr : dr.getMatchResults()) {
outcome.matches.addAll(mr.getMatchRecords());
}
}
}
}
return outcome;
}
}Controlling which sharing context the rule uses
DuplicateRuleHeader.runAsCurrentUser controls whose record visibility the matching uses. Apex normally runs in system mode, so by default it can match records that the running user cannot see. Setting runAsCurrentUser = true makes the rule respect the current user's access. This matters when the rule's scope setting enforces sharing rules (covered in the earlier chapter on sharing and rule conditions). If your code and your UI users get different matches for the same data, compare this setting first.
Bypassing duplicate rules
Apex has no switch that means "skip all duplicate rules." What you can do depends on the rule action and on who owns the configuration:
- Alert rules: pass
allowSave = true, as shown above. This is the intended bypass. - Block rules: the DML options cannot override these. Your choices are to change the rule, to deactivate it for the load, or to add a rule condition so the rule does not run for a specific integration user. Make those changes deliberately and tell the administrators who own the rule.
- API clients: the same options exist as the SOAP
DuplicateRuleHeaderand the REST headerSforce-Duplicate-Rule-Header. An example value isallowSave=true; includeRecordDetails=true.
Testing duplicate handling
Duplicate rules are metadata, so active rules apply inside Apex tests. Insert a seed record first, then insert a matching one and assert on the result. Remember that a test only passes in an org where the rule is active. If the rule is later deactivated, the test fails. Check that the rule fired, not only that a failure occurred, by asserting on getDuplicateRule().
Exercise
An Apex job inserts Contacts with Database.insert(list, false). A Contact rule has the action "Allow with alert", and a different rule on Account has the action "Block". The job sets DuplicateRuleHeader.allowSave = true. What happens to a Contact that matches an existing one, and to an Account that matches an existing one?
Show answer
The matching Contact is saved, because allowSave acknowledges the alert. The matching Account still fails, because allowSave cannot override a Block rule. Its SaveResult has isSuccess() false and a Database.DuplicateError whose DuplicateResult.isAllowSave() is false. Because allOrNone is false, the other records in the list are saved normally.