Sub topic 13
Adding a Bypass Switch for Data Loads and Tests
This chapter assumes you have read the earlier chapters. You should already have a logic-less trigger, a handler class, dispatch on Trigger.operationType, a recursion guard, and the reusable TriggerHandler base class. You should also know what governor limits are and how @IsTest classes work.
Why a handler needs an off switch
Handlers run on every DML statement against their object. That is usually what you want, but sometimes it is not:
- A one-time data migration loads millions of records. Your handler would create a
Taskfor each one and consume CPU time you don't need to spend. - A test needs 50
Accountrecords as background data. It does not want the handler to rewrite their descriptions or create follow-up tasks. - An integration user must write fields exactly as the source system sent them.
- A support engineer needs to repair bad data without triggering side effects.
The usual first response is to comment out the trigger or deactivate it. Both are bad ideas. Deactivating a trigger in production needs a deployment, it affects every user, and someone has to remember to turn it back on. A bypass switch is code that you control at run time, for a defined scope, and that turns itself off again.
The bypass in the base class
The base class from the previous chapter already holds the mechanism. Here it is in full, with the part that matters for this chapter.
public virtual class TriggerHandler {
private static Set<String> bypassed = new Set<String>();
public static void bypass(String handlerName) {
bypassed.add(handlerName);
}
public static void clearBypass(String handlerName) {
bypassed.remove(handlerName);
}
public void run() {
String description = String.valueOf(this);
String handlerName = description.substring(0, description.indexOf(':'));
if (!Trigger.isExecuting || bypassed.contains(handlerName)) {
return;
}
switch on Trigger.operationType {
when BEFORE_INSERT { beforeInsert(); }
when BEFORE_UPDATE { beforeUpdate(); }
when AFTER_INSERT { afterInsert(); }
when AFTER_UPDATE { afterUpdate(); }
when else { }
}
}
protected virtual void beforeInsert() {}
protected virtual void beforeUpdate() {}
protected virtual void afterInsert() {}
protected virtual void afterUpdate() {}
}Three details are worth understanding.
- The set is static. A static variable lives for one transaction. Every trigger, handler, and helper in that transaction sees the same set. This is why one call to
bypasscan affect a trigger that fires several steps later. - The handler name comes from
String.valueOf(this). For an Apex object this returns the class name, a colon, and the field values, for exampleAccountTriggerHandler:[]. The code keeps everything before the first colon. The result is the class name, so you can pass'AccountTriggerHandler'tobypass. - The
Trigger.isExecutingcheck. Outside a trigger theTriggercontext variables are empty. If someone callsrun()from another class, the method returns instead of failing on a nulloperationType.
A concrete handler that uses the base class
The handler extends the base class and overrides only the methods it needs. It keeps the same behavior as the earlier chapters.
public with sharing class AccountTriggerHandler extends TriggerHandler {
protected override void beforeInsert() {
for (Account acc : (List<Account>) Trigger.new) {
if (String.isBlank(acc.Description)) {
acc.Description = 'Created without a description';
}
}
}
protected override void afterInsert() {
List<Task> followUps = new List<Task>();
for (Account acc : (List<Account>) Trigger.new) {
followUps.add(new Task(WhatId = acc.Id, Subject = 'Welcome call'));
}
insert followUps;
}
}The trigger itself does not change. It subscribes to all events and calls the handler.
trigger AccountTrigger on Account (
before insert, before update, before delete,
after insert, after update, after delete, after undelete
) {
new AccountTriggerHandler().run();
}How the decision is made
On each trigger firing, the handler asks a few questions before any business logic runs.
Using the bypass safely in Apex
The bypass stays on until you clear it or the transaction ends. If your code throws an exception between bypass and clearBypass, the clear call never runs. Within the same transaction, any later DML on that object, possibly in code you did not write, silently skips the handler. Always clear the bypass in a finally block.
public with sharing class AccountMigrationService {
public static void loadHistoricalAccounts(List<Account> accounts) {
TriggerHandler.bypass('AccountTriggerHandler');
try {
insert accounts;
} finally {
TriggerHandler.clearBypass('AccountTriggerHandler');
}
}
}Keep the bypassed region as small as you can. Bypass around the single DML statement that needs it, not around a whole method. Anything else that touches Account inside the region will also skip the handler.
Bypassing in tests
Tests use the bypass in two ways. The first is to set up background data without running the handler's side effects. The second is to test the bypass itself, so you know the switch works.
@IsTest
private class TriggerHandlerBypassTest {
@IsTest
static void bypassedHandlerDoesNotRun() {
TriggerHandler.bypass('AccountTriggerHandler');
try {
insert new Account(Name = 'Bypassed');
} finally {
TriggerHandler.clearBypass('AccountTriggerHandler');
}
Account saved = [SELECT Description FROM Account WHERE Name = 'Bypassed'];
Assert.isNull(saved.Description, 'Handler should not have set a description');
Assert.areEqual(0, [SELECT COUNT() FROM Task WHERE WhatId = :saved.Id],
'Handler should not have created a follow-up task');
}
@IsTest
static void handlerRunsAgainAfterBypassIsCleared() {
TriggerHandler.bypass('AccountTriggerHandler');
TriggerHandler.clearBypass('AccountTriggerHandler');
insert new Account(Name = 'Normal');
Account saved = [SELECT Description FROM Account WHERE Name = 'Normal'];
Assert.areEqual('Created without a description', saved.Description);
}
}The second test matters more than it looks. It proves that clearBypass really restores normal behavior. Without it, a bug in the clear logic would leave handlers disabled and your other tests would still pass.
Each test method starts with fresh static state, so a bypass set in one test method does not leak into another. A bypass set in a @TestSetup method also does not carry over into the test methods, because setup runs in its own transaction. Set the bypass inside the test method that needs it.
Bypassing for loads outside Apex
A static set cannot help when the data comes from outside Apex. Data Loader, an integration, or an import wizard each open their own transaction, and no Apex code of yours runs before the trigger fires. For these cases the switch has to be stored as data or as a permission that the handler reads.
The least disruptive option is a custom permission. You assign it to the integration user or to a permission set. It is checked per user, and it needs no code change to turn on or off. Add the check to run().
public void run() {
String description = String.valueOf(this);
String handlerName = description.substring(0, description.indexOf(':'));
if (!Trigger.isExecuting
|| bypassed.contains(handlerName)
|| FeatureManagement.checkPermission('Bypass_' + handlerName)) {
return;
}
// ... switch on Trigger.operationType as before
}With this change, a custom permission with the API name Bypass_AccountTriggerHandler must exist before the check can return true. Anyone who holds it skips the Account handler, whether the DML comes from Data Loader, a flow, or Apex. Create the permission and put it in a permission set that you assign only for the duration of the load.
| Approach | Scope | Survives past one transaction | Works for external loads | Who controls it |
|---|---|---|---|---|
| Static set (`bypass`) | One transaction | No | No | Apex code |
| Custom permission | One user | Yes | Yes | Admin, through permission sets |
| Custom setting or custom metadata flag | Whole org, profile, or user | Yes | Yes | Admin, through setup or deployment |
Use the static set when Apex code knows exactly where it needs the bypass. Use a custom permission when a person or an integration needs to skip the handler for a period of time. Use a custom setting when you need a global kill switch.
Edge cases and risks
- Skipped logic includes validations. Anything your handler enforces, such as required fields or duplicate checks, is skipped too. After a bypassed load, run a report or script to check the data. The handler will not have done it for you.
- Other automation still runs. The bypass only affects this handler. Validation rules, flows, and other triggers on the object still fire. A bypass is not a way to turn off all automation.
- Cascading effects. If a bypassed handler normally updates a child object, the child handler is not bypassed. Its own bypass must be set separately. If you want to bypass a group of handlers, call
bypassonce for each. - Recursion guard interaction. The
processedIdsset from the recursion chapter is also static. A record skipped by a bypass is not added to it, so the first unbypassed run still processes the record normally. - Audit trail. Bypass switches are powerful. Limit who can hold the custom permission, and consider logging when it is used.
Exercise
A nightly integration inserts Contacts through the REST API as a dedicated integration user. The ContactTriggerHandler should not run for that user. Why does calling TriggerHandler.bypass('ContactTriggerHandler') in a utility class not work here, and what would you use instead?
Show answer
The REST API call starts its own transaction, and no Apex code of yours runs before the Contact trigger fires, so the static bypass set is empty when run() checks it. Use a switch that is stored outside the transaction, such as a custom permission named Bypass_ContactTriggerHandler assigned to the integration user. run() checks it with FeatureManagement.checkPermission and returns early.
Exercise
What is wrong with this code, and how do you fix it? TriggerHandler.bypass('AccountTriggerHandler'); insert accounts; update contacts; TriggerHandler.clearBypass('AccountTriggerHandler');
Show answer
If insert or update throws, clearBypass never runs, so later DML on Account in the same transaction also skips the handler. The bypass also covers the Contact update, which may fire code that updates Accounts. Wrap the insert in try/finally with clearBypass in the finally block, and move the contact update outside the bypassed region.