Understanding DmlException in Salesforce

Understanding DmlException
Chinmaya By Chinmaya
6 Min Read

Introduction

In Salesforce, DmlException is thrown when there is an issue with Data Manipulation Language (DML) operations like insert, update, delete, or undelete.
This is one of the most commonly encountered exceptions in Apex, and handling it effectively is crucial for creating robust applications.

In this blog, we will cover:

  1. What is a DmlException?
  2. Common causes of DmlException.
  3. Examples of scenarios that throw DmlException.
  4. How to handle DmlException.
  5. Best practices to avoid or manage DmlException

1. What is a DmlException?

A DmlException is a runtime error that occurs when a DML operation (such as insert or update or delete or upsert) fails to execute as expected.

These failures are often due to violations of Salesforce rules or constraints, such as validation rules, field integrity issues, or sharing violations.

2. Common Causes of DmlException

Here are the most frequent causes of DmlException:

a. Validation Rule Violations
Occurs when a record violates an active validation rule during a DML operation.

b. Required Field Missing
Happens when a required field is not provided in the record being inserted or updated.

c. Field Integrity Exceptions
Occurs when invalid data is assigned to a field, such as exceeding the character limit or using an invalid picklist value.

d. Sharing and FLS (Field-Level Security) Violations
Occurs when the user performing the operation doesn’t have the necessary permissions.

e. Mixed DML Operation
Occurs when a DML operation tries to update both setup and non-setup objects in the same transaction.

3. Examples of DmlException

Example 1: Validation Rule Violation

				
					try {
    Account acc = new Account(Name = '');
    insert acc; // Throws DmlException due to validation rule for non-empty Name
} catch (DmlException e) {
    System.debug('Dml Exception: ' + e.getMessage());
}
				
			

Example 2: Missing Required Field

				
					try {
    Contact con = new Contact(FirstName = 'John');
    insert con; // Throws DmlException because LastName is required
} catch (DmlException e) {
    System.debug('Dml Exception: ' + e.getMessage());
}
				
			

Example 3: Field Integrity Exception

				
					try {
    Account acc = new Account(Name = 'This name exceeds the maximum length allowed for the Name field...');
    insert acc; // Throws DmlException due to field length exceeding the limit
} catch (DmlException e) {
    System.debug('Dml Exception: ' + e.getMessage());
}
				
			

Example 4: Mixed DML Operation

				
					try {
    User user = [SELECT Id FROM User WHERE Username = 'testuser@example.com'];
    Account acc = new Account(Name = 'Test Account');
    insert acc; // Throws DmlException if Mixed DML rules are violated
} catch (DmlException e) {
    System.debug('Dml Exception: ' + e.getMessage());
}
				
			

4. How to Handle DmlException

Handling DmlException effectively ensures that your application can gracefully recover from errors and provide meaningful feedback to users.

a. Use Try-Catch Blocks

Wrap DML operations in try-catch blocks to catch and handle exceptions.

				
					try {
    Account acc = new Account(Name = '');
    insert acc;
} catch (DmlException e) {
    System.debug('Error: ' + e.getMessage());
}
				
			

b. Use Database.SaveResult for Partial Success

For bulk DML operations, use Database.insert() or Database.update() with allOrNone = false to allow partial success.

				
					List<Account> accounts = new List<Account>{
    new Account(Name = 'Valid Account'),
    new Account(Name = '')
};

Database.SaveResult[] results = Database.insert(accounts, false);
for (Database.SaveResult result : results) {
    if (!result.isSuccess()) {
        for (Database.Error err : result.getErrors()) {
            System.debug('Error Message: ' + err.getMessage());
        }
    }
}
				
			

5. Best Practices to Avoid DmlException

1. Validate Data Before DML Operations
Use Apex code to validate records before inserting or updating them.

				
					if (String.isEmpty(acc.Name)) {
    throw new IllegalArgumentException
    ('Name cannot be empty.');
}
				
			

2. Use Database Methods for Bulk DML
Use Database.insert() or Database.update() with allOrNone = false for batch operations to ensure partial success.

3. Handle Validation Rules Gracefully
Ensure records comply with validation rules before performing DML operations.

4. Avoid Mixed DML Operations
Use asynchronous methods like @future or Queueable to separate setup and non-setup object DML operations.

5. Monitor Required Fields
Check the metadata of objects to identify required fields and include them in your DML operations.

6. Check Field-Level Security
Use Apex’s isAccessible() or isCreateable() to ensure the user has appropriate field permissions.

				
					if (!Schema.sObjectType. Account. fields.Name .isCreateable()) {
    throw new IllegalAccess Exception ('User does not have permission to create Name field.');
}
				
			

7. Use Exception Logging
Log DmlException errors in a custom object for later analysis.

				
					public static void logError(String errorMessage) {
    Error_Log__c log = new Error_Log__c();
    log.Message__c = errorMessage;
    insert log;
}
				
			

6. Real-World Example: Handling Bulk DML with Validation

Scenario: Inserting Multiple Accounts with Partial Success

				
					public class AccountService {
    public static void insertAccounts (List<Account> accounts) {
        Database.SaveResult[] results = Database.insert(accounts, false);
        for (Database.SaveResult result : results) {
            if (!result.isSuccess()) {
                for (Database.Error err : result.getErrors()) {
                    System.debug('Error inserting account: ' + err.getMessage());
                }
            }
        }
    }
}
				
			

How It Works:

  1. Uses Database.insert() with allOrNone = false to handle partial success.
  2. Logs errors for each failed record without affecting successful inserts.

Conclusion

The DmlException is a common error in Salesforce that requires careful handling to ensure smooth operations.

By understanding its causes and using best practices like try-catch blocks, partial success methods, and validation checks, you can build robust applications that handle errors gracefully.

Share This Article
Follow:
Chinmaya is working as a Senior Consultant with a deep expertise in Salesforce. Holding multiple Salesforce certifications, he is dedicated to designing and implementing cutting-edge CRM solutions. As the creator of Writtee.com, Chinmaya shares his knowledge on educational and technological topics, helping others excel in Salesforce and related domains.
1 Comment