I am trying to achieve transactional rollback when i will get checked exception from "invokeProcedureForLead" method(code mentioned below). I have tried multliple ways and some reference still
it is not working for me .
For more understanding please find below code
#Transactional(rollbackFor = Exception.class)
public LeadResponseDTO processDataInDB(LMCRAResponseData lmcraResponse,
Boolean crnPresentFlag, Map<Integer, Integer> craProcData,
Map<Integer, Integer> crnProcData,LeadResponseDTO leadResponseDTO,LMCRARequestData lmcraRequestData) throws CRAProcessDBException,SQLException, CRAProcessClientException {
try{
leadResponseDTO = extractDecision(lmcraResponse,crnPresentFlag);
decisionEngineResponseDao.invokeProceduresForLead(craProcData, crnProcData, lmcraResponse);
}catch(Exception e){
log.error("error in invokeProcCalls", e);
if (masterErrorCodes.getErrorDTO("6006") != null)
logException(lmcraResponse, masterErrorCodes.getErrorDTO("6006"));
leadResponseDTO=new LeadResponseDTO();
getLeadResponseDTO(lmcraRequestData,leadResponseDTO,e.getMessage());
}
return leadResponseDTO;
}
public void invokeProceduresForLead(Map<Integer, Integer> craProcData,
Map<Integer, Integer> crnProcData, LMCRAResponseData lmcraResponseData) throws Exception {
int noCRNFlag = 0;
String commonLogs = CommonUtil.printDECommonLogs(lmcraResponseData);
if (lmcraResponseData.isBureauMatch() && crnProcData.isEmpty())
noCRNFlag = 1;
if (lmcraResponseData.isBureauMatch()
&& invokeProcLeads(craProcData, DBConstants.CALL_PROC_PROCESS_CRA_DATA_LEAD,
Integer.parseInt(lmcraResponseData.getCaseID())) != null) {
log.info("invokeProcLeads for Cra block - 1 for runId {} " , commonLogs);
throw new CRAProcessDBException("error in invokeProcCalls for CRA");
}
if (crnProcData != null
&& !crnProcData.isEmpty()
&& invokeProcLeads(crnProcData, DBConstants.CALL_PROC_PROCESS_CRN_DATA_LEAD,
Integer.parseInt(lmcraResponseData.getCaseID())) != null) {
log.info("invokeProcLeads for crn block - 2 for runId {} " , commonLogs);
throw new CRAProcessDBException("error in invokeProcCalls for CRN");
}
if (((crnProcData == null || crnProcData.isEmpty()) || !lmcraResponseData.isBureauMatch())
&& invokeNoCrnForLeads(DBConstants.CALL_PROC_PROCESS_NO_CRN_DATA_LEAD,
Integer.parseInt(lmcraResponseData.getCaseID()), noCRNFlag) != null) {
log.info("invokeNoCrnForLeads block - 3 for runId {} " , commonLogs);
throw new CRAProcessDBException("error in invokeProcCalls for NOCRN");
}
I think the code needs to change like this -
log.error("error in invokeProcCalls", e);
if (masterErrorCodes.getErrorDTO("6006") != null)
logException(lmcraResponse, masterErrorCodes.getErrorDTO("6006"));
leadResponseDTO=new LeadResponseDTO(); getLeadResponseDTO(lmcraRequestData,leadResponseDTO,e.getMessage());
}
throw e;
Note that **throw e; ** line added..
The problem is you are throwing an exception from internal call, but then swallowing it in outer method. So the exception is never thrown from outer method, which results in no rollback happening.
Related
i have a Problem with my Custom Exception, i want to throw a Custom Exception when the entered row/col does not excist in my shelf[][] which only kind of works. The custom exception does get thrown when i compile my main (error message is printed)- even though the throw part in my Code is apparently never reached (https://i.stack.imgur.com/1OY52.png) - but it also throws the ArrayIndexOutOfBoundsException. So when i Junit test my method for throwing InvalidRow/ColumnException it fails because it throws the ArrayOutOfBoundsException.
How do i solve this problem so my Junit test assertThrows(InvalidRowException.class,() -> shelf.addItem(3, 0, bottle)); doesnt catch the ArrayIndexOutOfBoundsException but instead only my InvalidRowException?
This is my Exception Class:
public class InvalidRowException extends ArrayIndexOutOfBoundsException {
public InvalidRowException(int wrongRow){
super("passed Row " + wrongRow + " doesnt excist.");
}
}
This is my Method
public void addItem(int row, int coll, Product product) throws InvalidRowException, InvalidColumnException {
if (row < 0 | row > shelf.length)
throw new InvalidRowException(row);
if (coll < 0 | coll > shelf[1].length)
throw new InvalidColumnException(coll);
try {
if (!(product instanceof Placeable)) {
throw new ProductNotPlaceableException(product);
} else if (shelf[row][coll] != null) {
System.out.println("Replacing product with serial " + shelf[row][coll].getSerialNumber()
+ " by product with serial " + product.getSerialNumber());
shelf[row][coll] = product;
} else {
shelf[row][coll] = product;
}
} catch (ProductNotPlaceableException e) {
System.out.println(e.getMessage());
}
}
You throw exception for
row > shelf.length
You should check for row > shelf.length -1 as arrays are 0 based
Similarly for coll the correct check is coll> shelf[row].length-1
I had a weird situation today while I was writing tests. Basically, I had a class with data. Let's say Toy for example, from which we can retrieve a name:
public class Toy {
private String name;
public Toy(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
And I had an exception, which was working in a way similar to this (e.g. just displaying data about all the objects on which we were working before it went bad); I also included a main for test purpose:
public class ToyFactoryException extends Exception {
public ToyFactoryException(Toy firstToy, Toy secondToy) {
super("An error occurred when manufacturing: " +
"\nfirstToy: " + firstToy != null ? firstToy.getName() : null +
"\nsecondToy: " + secondToy != null ? secondToy.getName() : null);
}
public static void main(String[] args) {
try {
throw new ToyFactoryException(null, new Toy("hi"));
} catch (ToyFactoryException myException) {
System.out.println("It should be there.");
} catch (Exception exception) {
System.out.println("But it's there instead.");
}
}
}
As I wrote in the first catch block, the exception should be caught in the ToyFactoryException.
However, in the exception, it's trying to read firstToy.getName() right here: firstToy != null ? firstToy.getName() : null
firstToy != null should evaluate to false, which means it shouldn't be trying to call firstToy.getName() in the first place. When you write it in the reverse order:
public ToyFactoryException(Toy firstToy, Toy secondToy) {
super("An error occurred when manufacturing: " +
"\nfirstToy: " + firstToy != null ? null : firstToy.getName() +
"\nsecondToy: " + secondToy != null ? secondToy.getName() : null);
}
You realise it reads null instead now, which means it's truly reading firstToy != null as true.
If you write the main this way instead (the null is the second parameter of the constructor):
public static void main(String[] args) {
try {
throw new ToyFactoryException(new Toy("hi"), null);
} catch (ToyFactoryException myException) {
System.out.println("It should be there.");
} catch (Exception exception) {
System.out.println("But it's there instead.");
}
}
It works properly, despite the secondToy ternary condition being written the same way as the firstToy ternary.
Why is the ternary condition on firstToy not evaluating null properly?
You should put parentheses around your conditional expression.
This:
"string " + firstToy != null ? firstToy.getName() : null
means this:
("string " + firstToy) != null ? firstToy.getName() : null
You need this:
"string " + (firstToy != null ? firstToy.getName() : null)
Code :
int i = MobStackHandler.this.getInstance().getConfigHandler().getMobStackingRadius();
List localList = MobStackHandler.this.mobList;
Iterator localIterator2;
for (Iterator localIterator1 = Bukkit.getServer().getWorlds().iterator(); localIterator1.hasNext(); localIterator2.hasNext())
{
World localWorld = (World)localIterator1.next();
localIterator2 = localWorld.getLivingEntities().iterator();
LivingEntity localLivingEntity = (LivingEntity)localIterator2.next();
if ((localList.contains(localLivingEntity.getType())) && (localLivingEntity.isValid())) {
for (Entity localEntity : localLivingEntity.getNearbyEntities(i, i, i)) {
if (((localEntity instanceof LivingEntity)) && (localEntity.isValid()) && (localList.contains(localEntity.getType()))) {
MobStackHandler.this.stackOne(localLivingEntity, (LivingEntity)localEntity, ChatColor.valueOf(MobStackHandler.this.getInstance().getConfigHandler().getMobStackColor()));
}
}
}
}
}
}.runTaskTimer(getInstance(), 40L, 40L);
}
Error: at com.obvious.handlers.MobStackHandler$1.run(MobStackHandler.java:87) ~[?:?]
As Oracle Doc
NoSuchElementException:
Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.
If you want to debug just debug your iteration.
I am getting this error.Return type is mismatched
public List<EmpRecord> Empdata(String uname) throws Exception {
System.out.println("Inside into service class2");
try {
#SuppressWarnings("unchecked")
List<EmpRecord> userObjs = hibernateTemplate.find("from EmpRecord u where u.uname=? ",uname);
if(userObjs.size() != 0) {
System.out.println(" Employee Name : " + userObjs.get(0).getEmpName());
}
return userobjs;
Typing error. Thats all there is to it. Use a capital O in userObjs in the return statement
change return userobjs; to return return userObjs;
I would also change if(userObjs.size() != 0) to if(userObjs!=null && userObjs.size() != 0) for safety reason.
How can I use assertEquals to see if the exception message is correct?
The test passes but I don't know if it hits the correct error or not.
The test I am running.
#Test
public void testTC3()
{
try {
assertEquals("Legal Values: Package Type must be P or R", Shipping.shippingCost('P', -5));
}
catch (Exception e) {
}
}
The method being tested.
public static int shippingCost(char packageType, int weight) throws Exception
{
String e1 = "Legal Values: Package Type must be P or R";
String e2 = "Legal Values: Weight < 0";
int cost = 0;
if((packageType != 'P')&&(packageType != 'R'))
{
throw new Exception(e1);
}
if(weight < 0)
{
throw new Exception(e2);
}
if(packageType == 'P')
{
cost += 10;
}
if(weight <= 25)
{
cost += 10;
}
else
{
cost += 25;
}
return cost;
}
}
Thanks for the help.
try {
assertEquals("Legal Values: Package Type must be P or R", Shipping.shippingCost('P', -5));
Assert.fail( "Should have thrown an exception" );
}
catch (Exception e) {
String expectedMessage = "this is the message I expect to get";
Assert.assertEquals( "Exception message must be correct", expectedMessage, e.getMessage() );
}
The assertEquals in your example would be comparing the return value of the method call to the expected value, which isn't what you want, and of course there isn't going to be a return value if the expected exception occurs. Move the assertEquals to the catch block:
#Test
public void testTC3()
{
try {
Shipping.shippingCost('P', -5);
fail(); // if we got here, no exception was thrown, which is bad
}
catch (Exception e) {
final String expected = "Legal Values: Package Type must be P or R";
assertEquals( expected, e.getMessage());
}
}
Works perfectly for me.
try{
assertEquals("text", driver.findElement(By.cssSelector("html element")).getText());
}catch(ComparisonFailure e){
System.err.println("assertequals fail");
}
if assertEquals fails ComparisonFailure will handle it
Java 8 solution
Here is a utility function that I wrote:
public final <T extends Throwable> T expectException( Class<T> exceptionClass, Runnable runnable )
{
try
{
runnable.run();
}
catch( Throwable throwable )
{
if( throwable instanceof AssertionError && throwable.getCause() != null )
throwable = throwable.getCause(); //allows "assert x != null : new IllegalArgumentException();"
assert exceptionClass.isInstance( throwable ) : throwable; //exception of the wrong kind was thrown.
assert throwable.getClass() == exceptionClass : throwable; //exception thrown was a subclass, but not the exact class, expected.
#SuppressWarnings( "unchecked" )
T result = (T)throwable;
return result;
}
assert false; //expected exception was not thrown.
return null; //to keep the compiler happy.
}
(taken from my blog)
Use it as follows:
#Test
public void testThrows()
{
RuntimeException e = expectException( RuntimeException.class, () ->
{
throw new RuntimeException( "fail!" );
} );
assert e.getMessage().equals( "fail!" );
}
Also, if you would like to read some reasons why you should not want to assertTrue that the message of your exception is equal to a particular value, see this: https://softwareengineering.stackexchange.com/a/278958/41811
This is nice library that allows asserting exceptions in a clean way.
Example:
// given: an empty list
List myList = new ArrayList();
// when: we try to get the first element of the list
when(myList).get(1);
// then: we expect an IndexOutOfBoundsException
then(caughtException())
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessage("Index: 1, Size: 0")
.hasNoCause();