Home > Net >  SonarQube Bug: Method throws alternative exception from catch block without history
SonarQube Bug: Method throws alternative exception from catch block without history

Time:10-27

In SonarQube scan it catches some bugs and it says method catches an exception, and throws a different exception, without incorporating the original Exception.

Look at the below code,

try {

   // something
   // can include nested exceptions...

} catch (CustomException ex) {
   throw ex;
} catch (Exception ex) {
   // Issue is here
   throw new CustomException(HttpStatus.INTERNAL_SERVER_ERROR, "exception message: "  ex);
}

Below is the Custom Exception DTO

class CustomException {
   HttpStatus status;
   String message;
    
   // Getter & Setter....
 }

I could solve this issue by doing,

catch (Exception ex) {
   CustomException exception = new CustomException(HttpStatus.INTERNAL_SERVER_ERROR, "message"   ex);
   exception.initCause(ex);
   throw exception;
}

The above solution is fine, but it's not ideal for the current situation, because I have to make a ton of changes then.

My question is, why is the below code not working. Is it because I am passing the ORIGINAL CAUSE as a STRING?

throw new CustomException(HttpStatus.INTERNAL_SERVER_ERROR, "exception message: "  ex);

If "ex" passed as a String is the issue, then is there a way to resolve it because My CustomException can take only "String" fields and I cannot change the type of any of the fields? Any suggestion?

CodePudding user response:

Sometimes doing the right thing requires that you "make a ton of changes". SonarQube is correct, losing the history (mostly - the stacktrace) is a real problem of your code.

You are free to ignore the warning or disable it somehow, but you cannot make it "a SonarQube bug" just because it's inconvenient.

The usual way to fix it would be to create another (or change existing) constructor of the CustomException class; or add the cause in each place it gets thrown. It might be a lot of work, but it can also be a life saver when you have a rare bug on production - and you can actually see where it originated.

CodePudding user response:

Typically, a custom exception class has an overloaded constructor that takes a String and a Throwable, and calls the super constructor with those parameters, and then sets any other class-specific properties. You would then change the " " to ",", and that likely will be more acceptable to SonarQube.

  • Related