JS rule flagging some code that may be ok

  • SonarQube server 8.5.1 (Enterprise 8.5.1.38104)
  • JavaScript/TypeScript Code Quality and Security 6.5.0.13383 (javascript)
  • sonar-scanner: 3.3.0.1492

This code is flagged as a bug due to the rule “Objects should not be created to be dropped immediately without being used”.

function isValidURL(url) {
  try {
    new URL(url);
    return true;
  } catch (e) {
    return false;
  }
}

This is somewhat ok code for testing a string whether it’s a valid URL. The URL constructor will throw on invalid URLs.

I wonder if there’s a way to test if a try/catch is being purposefully used to return a boolean, so that it could be inferred that it’s intentional? Or maybe it’s just new URL() that could be special cased?

Hello @mehulkar,

Thank for your message, and sorry for the delay.

We recently added an exception to the rule for such use of constructors in try-catch constructs. The exception has been implemented, and the new version of the rule will be part of the upcoming SonarQube 8.9 LTS release.

Best,
Yassin

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.