-
Notifications
You must be signed in to change notification settings - Fork 86
Open
Description
Currently, when an exception type is specified, the exception will be created using the parameterless constructor.
It would be nice if the exception message could be set using the (string message) constructor.
Here's one example of how to achieve that. It does so without any change in configuration so it would be a possibly unexpected change in behaviour for some users. It doesn't break any of the existing unit tests however.
I'd like some feedback on how you see the issue before actually making a pull request for it:
throw exceptionCustomizations.Customization.Match(
message => new ArgumentException(message: message ?? generalMessage, paramName: paramName),
type => Create(type, Combine(generalMessage, paramName)),
func => func(),
func => func(paramName));
static string Combine(string message, string paramName) => $"{message} (Parameter '{paramName}')";
static Exception Create(Type exceptionType, string message)
{
if (!Constructors.TryGetValue(exceptionType, out var constructor))
{
foreach (var constructorInfo in exceptionType.GetConstructors(Instance | Public | NonPublic))
{
var parameters = constructorInfo.GetParameters();
if (parameters.Length == 1 && parameters[0].ParameterType == typeof(string))
{
constructor = message => (Exception)constructorInfo.Invoke(new[] { message })!;
Constructors[exceptionType] = constructor;
return constructor(message);
}
}
Constructors[exceptionType] = null!;
}
return constructor?.Invoke(message) ?? (Exception)Activator.CreateInstance(type)!;
}
private static readonly Dictionary<Type, Func<string?, Exception>?> Constructors = new();Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels