fix: extra error messages
This commit is contained in:
@@ -85,9 +85,21 @@ namespace CarManagerV3
|
||||
/// A new <see cref="Car"/> instance.
|
||||
/// </returns>
|
||||
public static Car FromCsvString(string csv)
|
||||
{
|
||||
try
|
||||
{
|
||||
string[] parts = csv.Split(';');
|
||||
return new Car(int.Parse(parts[0]), parts[1], parts[2], int.Parse(parts[3]), parts[4], int.Parse(parts[5]), decimal.Parse(parts[6]));
|
||||
Car temp = new Car(int.Parse(parts[0]), parts[1], parts[2], int.Parse(parts[3]), parts[4], int.Parse(parts[5]), decimal.Parse(parts[6]));
|
||||
if (temp.Year < 1886 || temp.Year > DateTime.Now.Year + 1) throw new Exception($"Invalid year: {temp.Year}");
|
||||
if (temp.Mileage < 0) throw new Exception($"Mileage cannot be negative: {temp.Mileage}");
|
||||
if (temp.Price < 0) throw new Exception($"Price cannot be negative: {temp.Price}");
|
||||
return temp;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"Error parsing CSV Car string: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -4,6 +4,7 @@ using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
|
||||
|
||||
namespace CarManagerV3
|
||||
@@ -52,6 +53,7 @@ namespace CarManagerV3
|
||||
public static List<Car> ReadCars(string path)
|
||||
{
|
||||
List<Car> cars = new List<Car>();
|
||||
List<string> failedLines = new List<string>();
|
||||
try
|
||||
{
|
||||
using (StreamReader reader = new StreamReader(@path))
|
||||
@@ -61,7 +63,13 @@ namespace CarManagerV3
|
||||
{
|
||||
// Process the line
|
||||
if (line == "") continue;
|
||||
cars.Add(Car.FromCsvString(line));
|
||||
Car tmp = Car.FromCsvString(line);
|
||||
if (tmp == null)
|
||||
{
|
||||
failedLines.Add(line);
|
||||
continue;
|
||||
}
|
||||
cars.Add(tmp);
|
||||
}
|
||||
reader.Close();
|
||||
}
|
||||
@@ -69,6 +77,15 @@ namespace CarManagerV3
|
||||
{
|
||||
Console.Error.WriteLine($"Error reading cars from file: {ex.Message}");
|
||||
}
|
||||
if (failedLines.Count > 0)
|
||||
{
|
||||
Console.Error.WriteLine($"Warning: {failedLines.Count} lines could not be parsed and were skipped.");
|
||||
foreach (string failedLine in failedLines)
|
||||
{
|
||||
Console.Error.WriteLine($"Failed line: {failedLine}");
|
||||
}
|
||||
MessageBox.Show($"Warning: {failedLines.Count} lines in the file could not be parsed and were skipped. Check the console for details.", "Parsing Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
}
|
||||
return cars;
|
||||
}
|
||||
|
||||
@@ -92,6 +109,7 @@ namespace CarManagerV3
|
||||
} catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"Error saving cars to file: {ex.Message}");
|
||||
MessageBox.Show($"Error saving cars to file: {ex.Message}", "Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user