I have the following code:
if (errorList != null && errorList.count() > 0)
{
foreach (var error in errorList)
{
throw new Exception(error.PropertyName + " - " error.ErrorMessage, error.EntityValidationFailed);
}
}
Why does it only throw one exception when multiple errors are in the list?
Becasue exception breaks the code execution, if it is not handled.
So the code like:
foreach (var error in errorList)
{
try
{
throw new Exception(error.PropertyName + " - " error.ErrorMessage, error.EntityValidationFailed);
}
catch(...) {}
}
will raise multiple exceptions, to be precise errorList.Length
times, which will be handled by catch(..)
, inside the loop body, if not re-thrown from the catch(..)
, will remain there.
You can only throw a single exception, you could however create a bunch of Exceptions
and then throw an AggregateException
at the end.
var exceptions = new List<Exception>();
foreach (var error in errorList)
{
exceptions.Add(new Exception(error.PropertyName + " - " error.ErrorMessage, error.EntityValidationFailed));
}
if(exceptions.Any())
{
throw new AggregateException(exceptions);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With