From 8cedbcd89adfc5b9f363b49b2b4a3db655bc028e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 15 Feb 2026 11:48:55 -0600 Subject: add extensions for formatting model binding errors --- src/slskd/Common/CommonExtensions.cs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) 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; @@ -449,6 +450,39 @@ namespace slskd return sanitized; } + /// + /// Converts a ModelStateDictionary into a human-readable format. + /// + /// The ModelStateDictionary to format. + /// The formatted error string. + 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 })); + } + + /// + /// Returns the , the for the ModelError, or both if both are present. + /// + /// The ModelError from which to retrieve the error message. + /// The retrieved error message. + 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})"; + } + /// /// Determines whether the given object is a . /// -- cgit v1.2.3