I'm writing a batch class that I'm hoping can utilize some existing trigger code. However, the trigger code uses the addError
method, which causes my batch to fail with the message System.FinalException: SObject row does not allow errors
. I'm running this method in a try-catch block so I can gather all errors and send them in an email to the running user, but it appears I cannot catch this exception at all. I built the following POC to confirm the behavior:
public class TestFinalExceptionBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc){
return Database.getQueryLocator('SELECT Id FROM Foo__c');
}
public void execute (Database.BatchableContext bc, List<Foo__c> scope){
try {
for (Foo__c f : scope){
f.addError('Test');
}
} catch (System.FinalException f){
System.debug(f.getMessage());
} catch (Exception e) {
System.debug(e.getMessage());
}
}
public void finish(Database.BatchableContext bc){}
}
And my fears are confirmed - I cannot catch this exception. The crazy thing is though, I run similar code from execute anonymous, and it doesn't throw an error at all.
So, a few questions here: First, what would be the best way to overcome this problem? I'm hoping to change the existing code as little as possible. My first thought is using Trigger.isExecuting
but is there a better way?
Second, System.FinalException
doesn't seem to appear at all in the Apex Exceptions Documentation. Any idea why? It appears to be uncatchable like a LimitException
, and I'd love to have some confirmation of that from the docs. And along with that, can anyone shed some light on addError
and when it will cause an error and when it won't? And is it always uncatchable?
system.isBatch()
.