mirror of
https://github.com/nsnail/spectre.console.git
synced 2025-08-02 18:17:30 +08:00
Improve conversion error messages
When a conversion to an enum fails, list all the valid enum values in the error message. Message before this commit: > Error: heimday is not a valid value for DayOfWeek. Message after this commit: > Error: Failed to convert 'heimday' to DayOfWeek. Valid values are 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
This commit is contained in:
@ -42,6 +42,13 @@ public class CommandRuntimeException : CommandAppException
|
||||
return new CommandRuntimeException($"Could not find converter for type '{parameter.ParameterType.FullName}'.");
|
||||
}
|
||||
|
||||
internal static CommandRuntimeException ConversionFailed(MappedCommandParameter parameter, TypeConverter typeConverter, Exception exception)
|
||||
{
|
||||
var standardValues = typeConverter.GetStandardValuesSupported() ? typeConverter.GetStandardValues() : null;
|
||||
var validValues = standardValues == null ? string.Empty : $" Valid values are '{string.Join("', '", standardValues.Cast<object>().Select(Convert.ToString))}'";
|
||||
return new CommandRuntimeException($"Failed to convert '{parameter.Value}' to {parameter.Parameter.ParameterType.Name}.{validValues}", exception);
|
||||
}
|
||||
|
||||
internal static CommandRuntimeException ValidationFailed(ValidationResult result)
|
||||
{
|
||||
return new CommandRuntimeException(result.Message ?? "Unknown validation error.");
|
||||
|
@ -84,8 +84,18 @@ internal static class CommandValueResolver
|
||||
throw CommandRuntimeException.NoConverterFound(mapped.Parameter);
|
||||
}
|
||||
|
||||
object? value;
|
||||
try
|
||||
{
|
||||
value = converter.ConvertFromInvariantString(mapped.Value ?? string.Empty);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
throw CommandRuntimeException.ConversionFailed(mapped, converter, exception);
|
||||
}
|
||||
|
||||
// Assign the value to the parameter.
|
||||
binder.Bind(mapped.Parameter, resolver, converter.ConvertFromInvariantString(mapped.Value ?? string.Empty));
|
||||
binder.Bind(mapped.Parameter, resolver, value);
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user