Search code examples
javabatch-processingwebsphere-libertyjsr352

How to identify an exception(which is happened from ItemReader, readItem method) in ItemWriter


In JSR352 batch, I am running a partitioned step to create multiple JSON objects. Each thread, reads some data from oracle and write as JSON object. In some cases, the resultSet.next() getting timed out and throws an exception and going to close() method of ItemReader and ItemWriter class to cleanup any resources. which is perfectly fine. However I have some dao calls on close() method of writer. which needs to be executed when the writer gets completed. But when there's an exception on ItemReader, I am not sure how to get the exception details on close() method. If the exception occured on ItemReader, close() method should not execute the DAO call. Is there anyway to identify ItemReader exception in ItemWriter class.

@Override
public Object readItem() throws Exception {
    Map<String, Object> resultMap = new HashMap<>();
    if (firstObject && null != resultSet && resultSet.isBeforeFirst()) {
        firstObject = false;
        return columnMetaDataMap;
    }       
    else if (null != resultSet && resultSet.next()) {
        recordNumber++;
        for (int i = 1; i <= rsMetaData.getColumnCount(); i++) {
            resultMap.put("C" + i, resultSet.getObject(i));
        }
        return resultMap;
    }
    return null;

ItemWriter class close():

 @Override
    public void close() throws Exception {
        gsonWriter.endArray();
        gsonWriter.flush();
        gsonWriter.close();
        subjectAreaCode = categoryCode+"/"+subCategoryCode+"/";
        logger.info("***Exception catch from writer for the file:"+outFile+"\n"+stepcontext.getException());

        if (file.length() == 2) {
            file.delete();
            gahRptExecStatUpdDAO.updateBatchRptStatus(outFile, GAHRptStatusConstants.NO_ROWS_TO_PROC);
        }

Solution

  • If you have an ItemReadListener defined it will get control in the onReadError method, so you'd know you had an exception in the ItemReader. You could then put some flag into an object in the StepContext transient user data (setTransientUserData( )). In the ItemWriter close method you could get the transient user data out of the Step Context and act accordingly depending on what was in there.
    Or just set the flag from a catch block in the ItemReader to handle anything thrown from within the readItem.