views:

22

answers:

1

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:

  1. Create a CustomException up front, pass it as an argument to each validator method, calling CustomException.addError(String msg) each time a validation fails. At the end of calling all the validator methods, do if (validationResult.hasErrors()) throw validationResult; or something similar. Basically ask the exception if it wants to be thrown.
  2. 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 the CustomException and throw it.

Which is better? Why? Are there any other typical patterns for this sort of thing?

A: 

Step 1 seems to be the option used in some of the MVCs, like Struts, for sure. In fact, I think it is the prefer way compared to Step 2. I mean, if you intend to add the error strings to CustomException, why not just add it right when the validation fails? I think it makes your code cleaner and easier to read.

limc