Reputation: 43
Here's the basic structure of the code in which I am facing the issue.
@Transactional
void A(){
B();
// Can I identify transaction rollback here?
APICall(); // THIS SHOULD NOT BE CALLED IF THE TRANSACTION FAILS
}
void B(){
try{
C() // throws Null Pointer Exception
}catch(Exception e){
// logs the details
}
}
@Transactional
void C(){
D() // throws Null Pointer Exception
}
The entire problem is that APICall() in method A(). That API shouldn't be called if the transaction fails. Since C() doesn't catch the exception thrown by D(), the transaction (method C()) is rolled back and hence the outer transaction (method A()) will also be marked for the roll back. But since the method B() catches the NullPointerException thrown by C(), the execution of the instructions continues in method A() and APICall() method is called. But the transaction of method A() will be rolled back since the internal transaction was rolled back.
So is there a way to check if the transaction of method A() is marked for a rollback inside the method A() itself? So that I can prevent the APICall? Or the only way is to rethrow the caught exception in method B()?
Upvotes: 1
Views: 344
Reputation: 2109
With your current approach, I see several issues.
B()
is consumed, which is bad. why consuming exception is badA()
(when there is an exception in B()
), which is breaking the whole purpose of ExceptionsB()
methods, handling response from all of them in a single A()
would look very ugly.Why do you want to avoid using Exceptions for the very same reason they are built for? This situation calls for exception since the exception would not only provide you with break of flow, it will also provide you complete stack trace and you will be able to handle the situation in a much better way.
Upvotes: 1