Created
May 18, 2020 21:13
-
-
Save AmbreJuryeaAmole/8e3a1a13d4636aa6111a6a9a000593dc to your computer and use it in GitHub Desktop.
Trigger Bad example with try/catch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trigger CaseTrigger on Case (after insert) { | |
system.debug('***CaseTrigger begin'); | |
// In this example trigger we are simply wanting to flag at the Account level | |
// that the Account has a Case linked to it, which is a lookup field on Case | |
// so we wouldn't be able to do a rollup count. | |
// In reality we would also want to track deletes of Cases but that is skipped | |
// for demonstration purposes. | |
// bulk map of accounts that we need to update | |
map<Id, Account> accountsForUpdateMap = new map<Id, Account>(); | |
// find accounts to update | |
for(Case c : trigger.new){ | |
// if this case is linked to an account and we've not already tagged this account | |
if(c.AccountId != null && !accountsForUpdate.containsKey(c.AccountId)) | |
// add this account to the map | |
accountsForUpdate.put(c.AccountId, new Account(Id = c.AccountId, HasACase__c = true)); | |
} | |
// check to see if we need to perform DML | |
if(!accountsForUpdate.isEmpty()){ | |
try{ | |
// let's do the DML | |
update accountsForUpdate.values(); | |
} catch(dmlexception e){ | |
// ************ Assume the ACCOUNT update FAILED *********** | |
// If DML failed, ends up here | |
system.debug('Error updating account: ' + e); | |
} | |
} | |
// If we get this far in code, something may have failed and been caught above, or everything worked. | |
system.debug('Potential Success'); | |
// If anything were to go wrong in the above DML, since we do have a try/catch the server | |
// will NOT automatically rollback the changes. (In this instance the Cases in this trigger | |
// WOULD be inserted into the database. This is usually NOT desired since the | |
// Account data is inaccurate.) | |
// NO error would show on the calling page or calling code that fired this trigger. | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment