HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavaMinor

Making a job completed, rolling back on error

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
errorrollingbackcompletedmakingjob

Problem

I have the following construction in the program:

while(true) {
    
    try {
        JobManager.markJobCompleted(unitOfWork.getSqlFactory(), jobId, dataOut);
    } catch (DbLogicException e) {
        logger.error(JobManager.CANNOT_MARK_JOB_COMPLETED + jobId, e);
        try {
            unitOfWork.rollback();
        } catch (DbLogicException e1) {
            logger.error(UnitOfWork.CANNOT_ROLLBACK_TRANSACTION, e1);
            unitOfWork.closeSilently();
            return;
        }
        continue;
    }
    
  }


So, the logic is the following:

  • Trying to mark the job completed



  • If we fail, try to rollback transaction and proceed to next job item



  • If transaction rollback failed, something is seriously wrong here, aborting everything



This construction looks a little clumsy to me. Is there a way to refactor it so it would become... beautiful?

Solution

Yes.

  • Throw specialized exceptions like CannotMarkJobCompletedException and CannotRollbackTransactionException...



  • Make your toString() method on exceptions to return something you want what your logger to log



  • Instead of doing: ...CAN_..._COMPLETED + jobId, you may do: thrown exception already knows this jobId



  • Store the thrown exception in a variable and call your logger once



By doing all of that you will solve the problem of having nested try-catch blocks.

Context

StackExchange Code Review Q#2129, answer score: 6

Revisions (0)

No revisions yet.