CsvHelper
CsvHelper copied to clipboard
BadDataException thrown inside Read forcibly mangles the error message by passing it through "AddDetails" of CsvHelperException
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
- Use this setting:
configuration.ReadingExceptionOccurred = args =>
{
Console.WriteLine(args.Exception.Message);
return false;
};
- 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.
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
.
Guys, please add the ability to skip adding details to the exception message. This really creates a lot of problems.