I have a list of validations to run against an object, each a separate method which takes the object as a parameter.
As each validation fails, I will create an appropriate error message.
At the end of the validation process, I will throw a custom exception containing a list of all the error messages.
My question is, I've seen this done a couple of ways:
- Create a
CustomException
up front, pass it as an argument to each validator method, callingCustomException.addError(String msg)
each time a validation fails. At the end of calling all the validator methods, doif (validationResult.hasErrors()) throw validationResult;
or something similar. Basically ask the exception if it wants to be thrown. - Have each validation result return a string error message if there is an error, null if it passes. Save these in a list. At the end of calling all the validator methods, check if the list is non-empty, if so, create a new
CustomException
, iterate the list and add all the error messages to theCustomException
and throw it.
Which is better? Why? Are there any other typical patterns for this sort of thing?