JoshClose / CsvHelper

Library to help reading and writing CSV files
http://joshclose.github.io/CsvHelper/
Other
4.65k stars 1.05k forks source link

BadDataException thrown inside Read forcibly mangles the error message by passing it through "AddDetails" of CsvHelperException #2157

Open ldeluigi opened 1 year ago

ldeluigi commented 1 year ago

Describe the bug BadDataException is thrown from the Read function when "An inconsistent number of columns has been detected.". By passing this message to the base constructor, BadDataException forcibly replaces the exception message with the output of AddDetails, thus making it impossible to get the original "An inconsistent number of columns has been detected." message as string, for example inside a ReadingExceptionOccurred delegate implementation.

To Reproduce

  1. Use this setting:
    configuration.ReadingExceptionOccurred = args =>
        {
           Console.WriteLine(args.Exception.Message);
           return false;
        };
  2. Parse a CSV with inconsistent line columns.

Expected behavior I'd like to be able to retrieve the simpler message string without internal details in some way.

Rob-Hague commented 1 year ago

There is a (less than ideal) workaround, but it is not impossible:

https://github.com/JoshClose/CsvHelper/blob/7b3ed4d45af8385e732a42eb161b0d129736edb3/src/CsvHelper/CsvHelperException.cs#L141

CsvConfiguration config = new(CultureInfo.InvariantCulture)
{
    DetectColumnCountChanges = true
};
using StringReader sr = new("""
1
1,2
""");
using CsvReader csv = new(sr, config);
csv.Read();

try
{
    csv.Read();
}
catch (BadDataException bde)
{
    Console.WriteLine("\""+GetMessage(bde)+"\""); // "An inconsistent number of columns has been detected."
}

static string GetMessage(CsvHelperException e)
{
    int newLineIndex = e.Message.IndexOf(Environment.NewLine);
    return newLineIndex >= 0 ? e.Message.Substring(0, newLineIndex) : e.Message;
}

Perhaps CsvHelperException should expose an OriginalMessage or SummaryMessage, or displaying the extra details should be opt-out by configuration, similar to ExceptionMessagesContainRawData.

samirmammadli commented 8 months ago

Guys, please add the ability to skip adding details to the exception message. This really creates a lot of problems.