Skip to content

Instantly share code, notes, and snippets.

@douglascayers
Last active February 17, 2023 00:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save douglascayers/737c5571a9768f710730c4156fdefe34 to your computer and use it in GitHub Desktop.
Save douglascayers/737c5571a9768f710730c4156fdefe34 to your computer and use it in GitHub Desktop.
Demo of Apex Batch Job's finish method not running if exception occurs in its execute method (API v46.0)
public class DemoBatchJob implements Database.Batchable<SObject> {
public Database.QueryLocator start( Database.BatchableContext context ) {
System.debug( 'DemoBatchJob.start: ' + context );
return Database.getQueryLocator([ SELECT Id FROM Organization ]);
}
public void execute( Database.BatchableContext context, List<SObject> records ) {
System.debug( 'DemoBatchJob.execute: ' + context );
Integer i = 1 / 0; // cause exception
}
public void finish( Database.BatchableContext context ) {
System.debug( 'DemoBatchJob.finish: ' + context );
insert new FeedItem(
ParentId = UserInfo.getUserId(),
Body = JSON.serializePretty( context )
);
}
}
@IsTest
private class DemoBatchJobTest {
@IsTest
static void it_should_finish_with_errors() {
ID jobId;
try {
Test.startTest();
jobId = Database.executeBatch( new DemoBatchJob() );
Test.stopTest();
} catch ( Exception e ) {
// catch exception thrown in job's
// execute method so that test continues
}
AsyncApexJob job = [ SELECT Id, JobType, Status, NumberOfErrors, MethodName, ExtendedStatus, CompletedDate FROM AsyncApexJob WHERE Id = :jobId LIMIT 1 ];
System.debug( job ); // should output the job's status as completed and error count greater than zero
List<FeedItem> posts = [ SELECT Id, Body FROM FeedItem WHERE ParentId = :UserInfo.getUserId()];
System.debug( posts ); // should output the chatter post created in the job's finish method
System.assert( job.NumberOfErrors > 0, 'finish method should have reported errors' );
}
}
@douglascayers
Copy link
Author

douglascayers commented Jul 4, 2019

image

I would have expected the AsyncApexJob's status to be "Completed" and number of errors to be greater than 0.

I would have expected at least one FeedItem record to be logged because the job's finish method inserts one.

In a test class, it does not seem the batch job's finish method's is called if the execute method fails.

Further reading: https://salesforce.stackexchange.com/questions/268192/testing-an-apex-batch-method-execute-exception-incrementing-numberoferrors-in

@douglascayers
Copy link
Author

If you modify the DemoBatchJob class to not error in its execute method, then the debug log tells a very different story. The finish method is called.

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment