Here’s a comprehensive solution that addresses all three focus areas: proper error handling, duplicate rule enforcement awareness, and correct use of the allOrNone flag.
First, modify your merge operation to use the allOrNone parameter set to false. This allows you to process successful merges while capturing failures:
Database.MergeResult[] results = Database.merge(master, duplicates, false);
for(Database.MergeResult result : results) {
if(!result.isSuccess()) {
for(Database.Error err : result.getErrors()) {
System.debug('Merge failed: ' + err.getMessage());
}
}
}
Second, implement duplicate rule checking before the merge. Query active duplicate rules and their criteria to understand what might cause conflicts. You can use the DuplicateRule and DuplicateRuleMatchRule objects to inspect the active rules programmatically.
Third, wrap your merge logic in proper exception handling that specifically catches DmlException and inspects the error type. For duplicate rule violations, the error code will be DUPLICATE_VALUE. Your trigger should handle this gracefully:
try {
Database.MergeResult[] results = Database.merge(master, duplicates, false);
// Process results and handle errors
} catch(DmlException e) {
for(Integer i = 0; i < e.getNumDml(); i++) {
if(e.getDmlType(i) == StatusCode.DUPLICATE_VALUE) {
// Handle duplicate rule violation
System.debug('Duplicate rule violated: ' + e.getDmlMessage(i));
}
}
}
Additionally, consider implementing a Database.DMLOptions approach where you can specify allowDuplicates = true for specific merge operations that should bypass duplicate rules. This is useful for automated data quality processes where you’ve already validated the merge candidates.
For your post-merge cleanup logic, ensure it only executes for successful merges by checking the MergeResult.isSuccess() flag. This prevents your cleanup code from running on failed merge attempts.
Finally, implement comprehensive logging that captures the duplicate rule name, the matched records, and the specific criteria that triggered the violation. This will help your sales team understand why certain merges fail and allow them to make informed decisions about data quality exceptions.
The key insight is that Database.merge with allOrNone=false gives you granular control over partial success scenarios, while proper exception handling and duplicate rule awareness ensure your automation is robust in production environments with active data quality rules.
This draft is based on general Salesforce knowledge. It has not been verified against your specific version and environment. Practitioners: verify the steps and share your experience below.