Skip to content

Commit db6fe03

Browse files
author
machibuse
committed
Handle serialization exceptions in ToDiagnosticString method and add unit test to validate error handling logic
1 parent 20320e9 commit db6fe03

2 files changed

Lines changed: 14 additions & 1 deletion

File tree

Source/Porticle.Grpc.TypeMapper/ClassVisitor.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,8 @@ public class ClassVisitor(TaskLoggingHelper log, bool wrapAllNonNullableStrings,
3737
var isMessageClass = node.BaseList?.Types.Any(t => t.ToString().Contains("IMessage")) ?? false;
3838
if (isMessageClass)
3939
{
40-
node = node.AddMembers(MethodFromSource("public string ToDiagnosticString() { return System.Text.Json.JsonSerializer.Serialize(this); }"));
40+
node = node.AddMembers(MethodFromSource(
41+
"public string ToDiagnosticString() { try { return System.Text.Json.JsonSerializer.Serialize(this); } catch(Exception ex) { return \"Message Invalid - \" + ex.Message; } }"));
4142
}
4243

4344
return node;

Source/Porticle.Grpc.UnitTests/Tests.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,18 @@ public void TestToString()
4545
Assert.AreEqual(customDiagnosticMessage.ToString(), customDiagnosticMessage.ToDiagnosticString());
4646
}
4747

48+
[TestMethod]
49+
public void TestToStringError()
50+
{
51+
var message = new TestMessageMapped();
52+
53+
// Should crash when deserializing, because "SingleGuid" backend field ist an empty string and cannot be converted to a Guid
54+
var equatable = message.ToString();
55+
56+
// Expect Exception
57+
Assert.AreEqual(equatable.Split('-').First().Trim(), "Message Invalid");
58+
}
59+
4860
[TestMethod]
4961
public void TestWithoutNull()
5062
{

0 commit comments

Comments
 (0)