I am working on a Spring Batch application and I have the following doubt about what could be a smart way to handle exceptions. Following my situation: my job is composed by a single step. This single step contains a writer component that call an external API in order to write the current element on an external system. This is my writer class code:
@Component
public class NotaryWriter implements ItemWriter<NotaryDetails> {
//int counter = 1;
@Autowired
private WpService wpService;
public NotaryWriter(WpService wpService) {
super();
this.wpService = wpService;
}
@Override
public void write(List<? extends NotaryDetails> items) throws Exception {
items.stream().forEach(currentNotary -> {
System.out.println("NotaryWriter - WRITING OUTPUT: " currentNotary.toString());
try {
//System.out.println("############################################################################# NotaryWriter COUNTER: " this.counter);
int newNotaryPostId = this.wpService.insertOrUpdateNotaryAsWpPost(currentNotary);
//System.out.println("INSERTED or UPDATED NOTARY: " currentNotary.toString());
//counter ;
} catch (JsonProcessingException | UnsupportedEncodingException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
}
}
Basically the write() method call the insertOrUpdateNotaryAsWpPost() service method in order to call an external REST API and "write" the current element on an external system. This service method might return the exceptions listed in the catch.
What happens if one of these exception happens and the code enter in this catch? The element is skipped (it will not be written in the external system or my Job will fail?)
In case of Job failure how can I handle this situation in order to simply skip this record and go ahead with the others?
CodePudding user response:
You can do whatever you want when the error is caught. By default, the record will simply be skipped and the job will continue to process elements.
You can write the ID inside a database, you can retry, you can state how many times you want items to be skipped before stopping, etc. The behavior is highly configurable and it depends on your outcome.
As for reading materials, I highly recommend:
https://www.baeldung.com/spring-batch-skip-logic
https://www.baeldung.com/spring-batch-retry-logic
https://www.javadevjournal.com/spring-batch/spring-batch-listeners/