aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-02-15 11:48:55 -0600
committerJP Dillingham <jp@dillingham.me>2026-02-15 11:48:55 -0600
commit8cedbcd89adfc5b9f363b49b2b4a3db655bc028e (patch)
tree5eb55078a03aac809b5248d976d1158dc8f8f456 /src/slskd
parent68a2986dc8aa06df2c5526bbdbbb3fb7815e659a (diff)
downloadslskd-8cedbcd89adfc5b9f363b49b2b4a3db655bc028e.tar.gz
add extensions for formatting model binding errors
Diffstat (limited to 'src/slskd')
-rw-r--r--src/slskd/Common/CommonExtensions.cs34
1 files changed, 34 insertions, 0 deletions
diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs
index 815c0eb4..c189837c 100644
--- a/src/slskd/Common/CommonExtensions.cs
+++ b/src/slskd/Common/CommonExtensions.cs
@@ -29,6 +29,7 @@ namespace slskd
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
+ using Microsoft.AspNetCore.Mvc.ModelBinding;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
@@ -450,6 +451,39 @@ namespace slskd
}
/// <summary>
+ /// Converts a ModelStateDictionary into a human-readable format.
+ /// </summary>
+ /// <param name="dictionary">The ModelStateDictionary to format.</param>
+ /// <returns>The formatted error string.</returns>
+ public static string GetReadableString(this ModelStateDictionary dictionary)
+ {
+ if (dictionary == null || dictionary.IsValid)
+ {
+ return string.Empty;
+ }
+
+ return dictionary.Values
+ .Where(v => v.Errors.Any())
+ .Select(v =>
+ v.Errors
+ .Select(e => GetErrorAndOrExceptionMessage(e))
+ .Aggregate((a, b) => string.Join(", ", new[] { a, b })))
+ .Aggregate((a, b) => string.Join(" ", new[] { a, b }));
+ }
+
+ /// <summary>
+ /// Returns the <see cref="ModelError.ErrorMessage"/>, the <see cref="Exception.Message"/> for the ModelError, or both if both are present.
+ /// </summary>
+ /// <param name="error">The ModelError from which to retrieve the error message.</param>
+ /// <returns>The retrieved error message.</returns>
+ public static string GetErrorAndOrExceptionMessage(this ModelError error)
+ {
+ var ex = error?.Exception?.Message;
+ return string.IsNullOrEmpty(error?.ErrorMessage) ? ex :
+ string.IsNullOrEmpty(ex) ? error?.ErrorMessage : $"{error?.ErrorMessage} ({ex})";
+ }
+
+ /// <summary>
/// Determines whether the given object is a <see cref="Dictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="obj">The object to check.</param>