1

I had understanding that if batch apex execute method encounters an uncatchable/uncaught exception, then it stops the batch processing at that particular execution of execute method and does not execute remaining execute methods, if any.

However I am seeing exact opposite behaviour and the execution continues even after an exception is thrown in execute method of apex batch. This behaviour is making handling of errors using ApexBatchErrorEvent tricky as there are multiple Platform events fired for the same error in different execution of execute method.

I haven't found documentation explaining this behaviour. Attaching screenshot which displays logs generated for an exception in every execution of execute method. enter image description here

Thanks in advance for sharing your insights!!

3
  • 2
    A failure in one execute chunk does not affect execution of later chunks. These all happen regardless.
    – Phil W
    Commented Jan 25, 2022 at 15:24
  • What are you trying to achieve?
    – Phil W
    Commented Jan 25, 2022 at 15:30
  • I am trying to develop a logging mechanism based on BatchApexErrorEvent. And thought of sending error notification to user based on BatchApexErrorEvent. With this behaviour, it looks like there will be multiple notifications generated for the same error for which user only needs take action once.
    – Amit
    Commented Jan 25, 2022 at 15:36

1 Answer 1

3

The following point should be noted from the documentation (my emphasis):

Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records each. The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second fails, the database updates made in the first transaction aren’t rolled back.

This doesn't make it entirely clear, but every transaction is unaffected by errors in any of the others; a batch that requires 5 chunks will have execute called 5 times regardless of the number of execute calls that end with an exception.

If you want the batch to actually terminate on catchable exceptions (you cannot engineer for limit errors) and the contextual user has permissions you could always consider calling System.abortJob in the batch's catch exception handler(s). Note that this is not recommended because it requires effectively admin permissions.

Alternatively, you need to make sure your logging framework captures the batch job ID and only adds a new log record if one hasn't already been captured for that job ID.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .