using System;
using System.Collections.Generic;
using System.Linq;
namespace Learning
{
public class Item
{
public string Field1 { get; set; }
public string Field2 { get; set; }
public int IntField { get; set; }
}
public class ValidationError
{
public string Message { get; set; }
}
public class ValidationException : Exception
{
private IEnumerable<ValidationError> _errors;
public ValidationException(IEnumerable<ValidationError> errors)
{
_errors = errors;
}
public IEnumerable<ValidationError> Errors { get { return _errors; } }
}
class Program
{
static void Main(string[] args)
{
var items = new List<Item>();
for (int i = 0; i < 10; i++)
{
items.Add(new Item { Field1 = "", Field2 = "content", IntField = i });
}
// Validate Items returns a list of validation errors, this can be
// used to control flow of program
var validationResults = ValidateItems(items, 5);
if (validationResults.Count != 0)
{
Console.WriteLine($"Enountered {validationResults.Count} errors");
}
try
{
// OperationThatValidates returns a result, so it notifies of errors
// via exceptions
var result = OperationThatValidates(items, 5);
}
catch (ValidationException ve)
{
Console.WriteLine($"{ve.Errors.Count()} validation failures!");
}
catch (AggregateException ae)
{
Console.WriteLine($"{ae.InnerExceptions.Count} exeptions encountered");
}
try
{
var result = OperationThatValidates(items, 30);
}
catch (ValidationException ve)
{
Console.WriteLine($"{ve.Errors.Count()} validation failures!");
}
catch (AggregateException ae)
{
Console.WriteLine($"{ae.InnerExceptions.Count} exeptions encountered");
}
}
public static ICollection<ValidationError> ValidateItems(List<Item> items, int requiredMinValue)
{
var validationErrors = new List<ValidationError>();
for (int i = 0; i < items.Count; i++)
{
if (items[i].IntField < requiredMinValue)
{
validationErrors.Add(new ValidationError { Message = $"Value must be >= {requiredMinValue}" });
}
}
return validationErrors;
}
public static string OperationThatValidates(List<Item> items, int minValue)
{
var validationResults = ValidateItems(items, minValue);
if (validationResults.Count > 0)
{
// Validation failed, so throw an exception. We only need to throw a single exception,
// Because we haven't encountered any exceptions so far since ValidateItems doesn't throw
// So use the custom exception type to return important information
throw new ValidationException(validationResults);
}
foreach (var item in items)
{
List<Exception> failures = new List<Exception>();
try
{
OperationThatThrows(item);
}
catch (Exception ex)
{
failures.Add(ex);
}
if (failures.Count != 0)
{
// Throw AggregateException because one of more exceptions has been encountered
// and we need to keep information about all of them.
throw new AggregateException("Unexpected Errors", failures);
}
}
return "This is the result you were hoping for";
}
private static void OperationThatThrows(Item item)
{
throw new NotImplementedException();
}
}
}