Skip to content

Commit c18e848

Browse files
authored
Pretty print type names in converter exceptions (#45)
1 parent 6463c88 commit c18e848

File tree

3 files changed

+37
-1
lines changed

3 files changed

+37
-1
lines changed

src/Vertical/CommandLine/Conversion/ConversionException.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,9 @@ internal ConversionException(string context, Type targetType, string argumentVal
4848
// Formats the exception message.
4949
private static string FormatMessage(string context, Type targetType, string argumentValue)
5050
{
51-
return $"{context}: could not convert {Formatting.Quote(argumentValue)} to target type {targetType.Name}.";
51+
var friendlyTargetType = TypeHelpers.GetFriendlyDisplayName(targetType);
52+
53+
return $"{context}: could not convert {Formatting.Quote(argumentValue)} to target type {friendlyTargetType}.";
5254
}
5355
}
5456
}

src/Vertical/CommandLine/Infrastructure/TypeHelpers.cs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,5 +101,28 @@ internal static string GetGenericTypeName(string typeName)
101101
var markerIndex = typeName.IndexOf('`');
102102
return markerIndex > -1 ? typeName.Substring(0, markerIndex) : typeName;
103103
}
104+
105+
internal static string GetFriendlyDisplayName(Type type)
106+
{
107+
try
108+
{
109+
if (!type.IsGenericType)
110+
return type.Name;
111+
112+
var genericTypeName = type.GetGenericTypeDefinition().Name;
113+
var tickIndex = genericTypeName.IndexOf('`');
114+
var trimmedTypeName = genericTypeName.Substring(0, tickIndex);
115+
var typeParams = type
116+
.GetGenericArguments()
117+
.Select(GetFriendlyDisplayName);
118+
var typeParamString = string.Join(",", typeParams);
119+
120+
return $"{trimmedTypeName}<{typeParamString}>";
121+
}
122+
catch
123+
{
124+
return type.Name;
125+
}
126+
}
104127
}
105128
}

test/Infrastructure/TypeHelpersTests.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
// or refer to https://opensource.org/licenses/MIT
66

77
using System;
8+
using System.Collections.Generic;
89
using Shouldly;
910
using Vertical.CommandLine.Infrastructure;
1011
using Xunit;
@@ -20,5 +21,15 @@ public void GetKnownMethodInfoThrowsForInvalidMethod()
2021
Array.Empty<Type>(),
2122
typeof(void)));
2223
}
24+
25+
[Theory]
26+
[InlineData(typeof(string), "String")]
27+
[InlineData(typeof(int), "Int32")]
28+
[InlineData(typeof(int?), "Nullable<Int32>")]
29+
[InlineData(typeof(Dictionary<int?, string>), "Dictionary<Nullable<Int32>,String>")]
30+
public void GetFriendlyNameReturnsExpected(Type type, string expected)
31+
{
32+
TypeHelpers.GetFriendlyDisplayName(type).ShouldBe(expected);
33+
}
2334
}
2435
}

0 commit comments

Comments
 (0)