Sub topic 2
Triggers, `addError`, and Failing the Whole Save
Assume you know basic Apex syntax, DML, try/catch, and governor limits. This chapter focuses on how triggers affect a transaction and how savepoints control rollback.
Triggers and `addError`
A trigger can call addError on an sObject to reject that record. The current save operation then fails. With normal all-or-none DML, no record in that DML statement is saved.
trigger ContactValidation on Contact (before insert) {
for (Contact c : Trigger.new) {
if (String.isBlank(c.Email)) {
c.addError('Email is required');
}
}
}If an insert includes several Contacts and one receives an error, the DML statement raises a DmlException. The trigger does not need to throw the exception itself.
Catching an Exception
Catching an exception only handles the error. It does not automatically undo DML that already succeeded.
insert new Account(Name = 'Kept');
try {
insert new Account(); // Name is required
} catch (DmlException e) {
System.debug(e.getMessage());
}
// The first Account remains if the transaction later completes normally.An unhandled exception rolls back the transaction. A handled exception lets the transaction continue, so earlier work can be committed.
Setting and Using a Savepoint
Database.setSavepoint() records a position in the current transaction. Database.rollback(sp) removes database changes made after that position.
Savepoint sp = Database.setSavepoint();
try {
Account a = new Account(Name = 'Acme Test');
insert a;
insert new Contact(
LastName = 'Doe',
AccountId = a.Id
);
} catch (DmlException e) {
Database.rollback(sp);
System.debug('Rolled back: ' + e.getMessage());
}A rollback does not end the transaction. Code can continue after it, but changes before the savepoint remain.
Savepoint Invalidation
Rolling back to an earlier savepoint invalidates savepoints created after it. Do not try to use an invalidated savepoint.
Savepoint sp1 = Database.setSavepoint();
insert new Account(Name = 'A');
Savepoint sp2 = Database.setSavepoint();
insert new Account(Name = 'B');
Database.rollback(sp1);
Database.rollback(sp2); // Runtime error: sp2 is invalidExercise
If the first Account insert succeeds, a later insert fails, and the exception is caught without a rollback, what happens to the first Account?
Show answer
It remains and can be committed when the transaction completes normally.