I'm often finding the need to validate a set of conditions, and instead of failing early (returning false or throwing an exception when the first condition is not fulfilled), I need to aggregate the results and report the individual failures.
I'm currently either using a list with custom entries (basically an entry consists of the type of the failure and some informative message) or some kind of observer (which also just aggregates the failures), but I have a feeling that this should be a common problem and that there should be some existing pattern for solving this.
Tasks Module Example Public Sub Main() Dim task1 = Task. Run(Sub() Throw New CustomException("This exception is expected!")) Try task1. Wait() Catch ae As AggregateException ' Call the Handle method to handle the custom exception, ' otherwise rethrow the exception. ae.
In C#, we manage exception handling using the try-catch block. Multiple exceptions can be caught separately or at once, depending on the developer's choice.
When using await, it's going to unwrap the first exception and return it, that's why we don't hit the catch (AggregateException e) line. But if we use something like the below code sample, we catch the AggregateException , note that it's not a good idea since we're blocking the running thread.
catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception. finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown.
Yes, it is a common problem, and both your approaches are good.
javax.validation.Validator
, which is the standard for java validation, uses the former. It returns a Set
of ConstraintViolations
s
If it fits your case, I would recommend using javax.validation
instead of something custom. It's a spec with multiple providers, one of which is hibernate-validator (no need to use hibernate to use the validation project)
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