Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate exceptions

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.

like image 747
pmf Avatar asked May 09 '11 15:05

pmf


People also ask

How do you handle aggregate exception?

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.

Can we throw multiple exceptions in C#?

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.

Does await throw AggregateException?

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.

What is try catch finally in C#?

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.


1 Answers

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 ConstraintViolationss

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)

like image 61
Bozho Avatar answered Oct 06 '22 01:10

Bozho