AI 生成的代码可能包含 OWASP Top 10 相关漏洞或潜在 Bug。本文根据 Qiita 原文,介绍如何使用以前称为 SonarLint 的 SonarQube IDE,在 IDE 中分析生成代码。

安装到 VS Code

SonarQube IDE 支持 VS Code、Cursor、Windsurf、Trae、JetBrains 和 Eclipse 等环境。在 VS Code 扩展市场搜索 SonarQube 并点击 Install。安装后即可实时分析正在编写的代码。

在 VS Code 扩展中安装 SonarQube IDE

在 VS Code 中实时分析代码

分析 AI 生成的代码

原文在 VS Code 终端中使用 Claude Code 生成一个 Three.js 网页,用 3D 像素风展示 SonarQube Logo。用 SonarQube IDE 打开生成的 index.html 后,可以发现错误和漏洞;点击问题还可以查看修复建议。

1
create a webpage which can show the sonarqube logo in 3d pixel style using threeJS. The page need to be interactiveabe like zoom in and out. Make the page a clear production-ready and detailed the pixel looks.

AI 生成的网页

生成的 3D SonarQube Logo

例如,下面的代码在发生错误时只输出含糊的日志,没有妥善处理问题:

1
2
3
4
5
6
try {
  return chargeCard(amount, cardNumber);
} catch (error) {
  console.log("Error occurred");
  return false;
}

即使页面能够正常显示,错误处理仍可能不充分。检查 IDE 的提示并改进日志和异常处理,有助于提升代码质量。

SonarQube IDE 分析结果与修复建议

连接服务器进一步管理

将 SonarQube IDE 连接到 SonarQube Server 后,可以集中管理团队成员本地分析的结果,并查看技术债务和安全风险。还可以集成 Jenkins 或 GitHub Actions,在每次构建时运行分析并使用 Quality Gate。服务器端的报告和趋势图也便于跟踪质量改进情况。

总结

IDE 分析可以尽早发现 AI 编写代码中的潜在问题。再结合服务器和 CI/CD,可从个人编辑阶段扩展到团队质量管理。