Skip to content

AfterInsert.ContinueOnError ​

Log and swallow the handler's exceptions, so later handlers still run and the insert goes on.

Signature

apex
public interface ContinueOnError {
}

AfterInsert.ContinueOnError has no methods: implementing it is the whole opt-in.

Example

apex
public with sharing class ContactWriter implements AfterInsert.Writer, AfterInsert.ContinueOnError {
    public Boolean writeOnAfterInsertWhen(TriggerTypes.InsertRecord record) {
        return record.isNotNull(Contact.AccountId);
    }

    public void writeOnAfterInsert(TriggerTypes.InsertRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        unitOfWork.toInsert(new Task(WhatId = ((Contact) record.getNewSObject()).AccountId, Subject = 'Review contact'));
    }
}
cls
public with sharing class AccountWelcomeTaskWriter implements AfterInsert.Writer, AfterInsert.ParentQuery, AfterInsert.ContinueOnError {
    public Map<SObjectField, TriggerTypes.ParentFields> queryParentsOnAfterInsert() {
        return new Map<SObjectField, TriggerTypes.ParentFields>{ Account.OwnerId => TriggerTypes.ParentFields.with(User.Name, User.Email) };
    }

    public Boolean writeOnAfterInsertWhen(TriggerTypes.InsertRecord record) {
        return record.startsWith(Account.Type, 'Customer');
    }

    public void writeOnAfterInsert(TriggerTypes.InsertRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        Account newAccount = (Account) record.getNewSObject();
        User owner = (User) record.getNewParent(Account.OwnerId);

        unitOfWork.toInsert(
            new Task(
                WhatId = record.getId(),
                OwnerId = newAccount.OwnerId,
                Subject = 'Onboarding call - ' + newAccount.Name,
                Description = 'New customer assigned to ' + owner?.Name + ' (' + owner?.Email + '). Confirm the billing address and the primary contact.',
                ActivityDate = Date.today().addDays(3),
                Priority = 'High',
                Status = 'Not Started'
            )
        );
    }
}

Rules ​

  • The rest of the handler is skipped. After an exception, its remaining records and its Finalizer do not run.
  • A Writer gets the automatic unit of work. It commits right after the Writer, so a failure never touches other Writers' writes.
  • Add a Logger. Without one, a swallowed exception leaves no trace.

WARNING

Some errors still fail the insert. Library exceptions, System.LimitException, EventBus.RetryableException (a platform event subscriber asking for redelivery), the FinalException from writing a trigger row and exceptions outside the handler's own methods, such as bypassOnAfterInsertWhen() or the final commit, are never swallowed.