debugjavaMinor
Making a job completed, rolling back on error
Viewed 0 times
errorrollingbackcompletedmakingjob
Problem
I have the following construction in the program:
So, the logic is the following:
This construction looks a little clumsy to me. Is there a way to refactor it so it would become... beautiful?
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.
By doing all of that you will solve the problem of having nested
- Throw specialized exceptions like
CannotMarkJobCompletedExceptionandCannotRollbackTransactionException...
- 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 thisjobId
- 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.