Home > Back-end >  Add exception handling into Spring's batch ItemProcessor
Add exception handling into Spring's batch ItemProcessor

Time:09-13

I am using the Spring ItemProcessor<I, O> to perform batch jobs. The issue is I have a lot of boilerplate code and 20 classes that implement the ItemProcessor<I, O>, each with different I and O.

My issue is I need to surround each process() implementation with a try {} catch () {} block. My first instinct is to create an abstract class with method overloading, but I'm not sure how I'd define each of the input and out in the ItemProcessor<I, O> in the child classes.

How can I implement exception handling to all of these ItemProcessor<I, O> implementations?

Example code:

@Component
@Slf4j
public class ProfileProcessor implements ItemProcessor<List<ProfileData>,List<AcquirerProfile>>{

    @Override
    public List<Profile> process(List<Profile> profileDataList) {
        code...
        return profiles;
    }
}
@Component
@Slf4j
public class Example2 implements ItemProcessor<List<ExampleData>,List<Example>>{

    @Override
    public List<Example> process(List<Example> exampleList) {
        code...
        return examples;
    }
}

The goal is to surround each of these implementations in try catch blocks.

CodePudding user response:

You can register an ExceptionHandler in your simple of fault-tolerant step with org.springframework.batch.core.step.builder.AbstractTaskletStepBuilder#exceptionHandler. This is the extension point that allows you to handle any exception that might happen while processing items.

  • Related