SonarQube提示条件始终为true,代码第2行遇此问题求解决办法
Got it, let's tackle this SonarQube warning you're seeing on line 2 of your code. The issue likely comes from SonarQube's static analysis incorrectly assuming Server.GetLastError() never returns null—but in reality, this method does return null when there are no unhandled exceptions to retrieve. Here are a few solid fixes:
Option 1: Use C# Pattern Matching (Cleanest Approach)
Upgrade your null checks and type casting to use modern C# pattern matching. This makes your code more readable and helps SonarQube correctly recognize that the null check is necessary:
var exe = Server.GetLastError(); if (exe is not null) { var errorInfo = exe.GetBaseException(); // Pattern match to check type and assign in one step if (errorInfo is HttpException error) { isNotFound = error.GetHttpCode() == (int)System.Net.HttpStatusCode.NotFound; } }
Option 2: Explicitly Inform SonarQube
If you need to keep your original code structure, add a comment to tell SonarQube that the null check is intentional and valid. This suppresses the false positive warning:
Exception exe = Server.GetLastError(); // SonarQube ignore: Server.GetLastError() returns null when no unhandled exception exists if (exe != null) { Exception errorInfo = exe.GetBaseException(); var error = errorInfo as HttpException; if (error != null) isNotFound = error.GetHttpCode() == (int)System.Net.HttpStatusCode.NotFound; }
Why This Happens
SonarQube's static analysis doesn't always account for all runtime scenarios of framework methods like Server.GetLastError(). While it might seem like the exe != null condition is always true in some code paths, the method can absolutely return null, so your check is valid—you just need to help SonarQube understand that.
内容的提问来源于stack exchange,提问作者Ankit Mori

