Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In spring-batch, how can I get the exception when there is a chunk error?

Tags:

spring-batch

Spring batch provides a listener for capturing when a chunk error has occurred (either the @AfterChunkError annotation or the ChunkListener.afterChunkError interface). Both receive the ChunkContext and the API says:

Parameters:

context - the chunk context containing the exception that caused the underlying rollback.

However, I don't see anything on the ChunkContext interface that would get me to the exception. How do I get from the ChunkContext to the relevant exception?

like image 396
dennislloydjr Avatar asked Oct 30 '25 20:10

dennislloydjr


2 Answers

Exception is located in ChunkListener.ROLLBACK_EXCEPTION_KEY attribute:

context.getAttribute(ChunkListener.ROLLBACK_EXCEPTION_KEY)
like image 183
Andrii Sysoiev Avatar answered Nov 02 '25 11:11

Andrii Sysoiev


Instead of implementing a ChunkListener you could implement one or more of ItemReadListener, ItemProcessListener and ItemWriteListener (or more simply ItemListenerSupport).

They respectively give acces to :

void onReadError(java.lang.Exception ex)
void onProcessError(T item, java.lang.Exception e)
void onWriteError(java.lang.Exception exception, java.util.List<? extends S> items)

I know this forces you to implement multiple methods to manage every aspect of a chunk, but you can write a custom method which takes an Exception and call it from these 3 methods.

like image 30
Thrax Avatar answered Nov 02 '25 12:11

Thrax