From 37dec51574ccc2df76f88801a31cc9b1b08af62c Mon Sep 17 00:00:00 2001 From: Erik Ruggles Date: Mon, 4 Oct 2021 15:06:43 -0500 Subject: [PATCH] Prevent divide by zero error When there were no hits or misses against a node, the result being returned was NaN as a result of a divide by zero issue. This approach converts the NaN result to a zero. --- Program.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Program.cs b/Program.cs index 7ef429c..4cb0895 100644 --- a/Program.cs +++ b/Program.cs @@ -335,7 +335,7 @@ private static void Main(string[] args) channel = "Hit Rate", unit = PRTGUnit.Percent, Float=1, - value = (Convert.ToDouble(statsInfo.SingleOrDefault(i => i.Key.Equals("keyspace_hits")).Value) / (Convert.ToDouble(statsInfo.SingleOrDefault(i => i.Key.Equals("keyspace_hits")).Value) + Convert.ToDouble(statsInfo.SingleOrDefault(i => i.Key.Equals("keyspace_misses")).Value))).ToString() + value = SafeGetFloat(() => (Convert.ToDouble(statsInfo.SingleOrDefault(i => i.Key.Equals("keyspace_hits")).Value) / (Convert.ToDouble(statsInfo.SingleOrDefault(i => i.Key.Equals("keyspace_hits")).Value) + Convert.ToDouble(statsInfo.SingleOrDefault(i => i.Key.Equals("keyspace_misses")).Value))).ToString()) } }, { @@ -405,5 +405,20 @@ private static string SafeGetInt32(Func func) return "0"; } } + + private static string SafeGetFloat(Func func) + { + try + { + var result = func(); + return result.Equals("NaN", StringComparison.InvariantCultureIgnoreCase) ? "0" : result; + + } + catch (Exception ex) + { + Trace.TraceError(ex.ToString()); + return "0"; + } + } } } \ No newline at end of file