ConvertToSingleString

Extension

Converts a collection of Error objects into a formatted multi-line string. Each error is rendered using a caller-supplied extractor function, allowing any property of the error to be used as the line content.

Returns an empty string when the collection is null or empty, making it safe to call unconditionally.

Signature

public static string ConvertToSingleString(
    this ICollection<Error> errors,
    Func<Error, string> errorInfoExtractorFunc,
    string prefixText = "Error(s):"
)

Parameters

NameTypeDescription
errorsICollection<Error>The collection of errors to format. Null or empty produces an empty string.
errorInfoExtractorFuncFunc<Error, string>A function applied to each error to produce the line content. For example e => e.Description or e => e.TechnicalDetail.
prefixTextstringThe first line of the output string. Defaults to "Error(s):". Pass an empty string to omit the prefix.

Returns

ValueWhen
string (multi-line)Prefix text followed by one error per line, separated by newlines.
string.EmptyWhen errors is null or empty.

Output Format

Error(s):
First error description
Second error description
Third error description

Examples

using Gubbins.Conversion;
using Gubbins.Models;

// --- Display user-facing error descriptions ---
List<Error> errors = new List<Error>
{
    new Error("Name is required."),
    new Error("Email must be a valid address."),
    new Error("Date of birth must be in the past.")
};

string message = errors.ConvertToSingleString(e => e.Description ?? string.Empty);
Console.WriteLine(message);
// Error(s):
// Name is required.
// Email must be a valid address.
// Date of birth must be in the past.

// --- Use technical details for logging ---
string logMessage = errors.ConvertToSingleString(
    e => e.TechnicalDetail ?? e.Description ?? "Unknown error",
    prefixText: "Validation failed:"
);
logger.LogWarning(logMessage);

// --- From a Result ---
Result result = SaveRecord(record);

if (result.Failed)
{
    string summary = result.Errors.ConvertToSingleString(
        e => e.Description ?? string.Empty
    );
    return BadRequest(summary);
}

// --- Custom prefix ---
string displayText = errors.ConvertToSingleString(
    e => e.Description ?? string.Empty,
    prefixText: "Please fix the following:"
);
// Please fix the following:
// Name is required.
// Email must be a valid address.

// --- No prefix ---
string bare = errors.ConvertToSingleString(
    e => e.Description ?? string.Empty,
    prefixText: string.Empty
);
// Name is required.
// Email must be a valid address.

// --- Empty collection returns empty string (safe to call unconditionally) ---
List<Error> noErrors = new List<Error>();
string empty = noErrors.ConvertToSingleString(e => e.Description ?? string.Empty);
Console.WriteLine(empty == string.Empty); // true