I'm building an API in C#, how should I return validation error messages when properties are set to invalid values? Should I throw exceptions or do something else? What do you recommend? I could use the AggregateException class from the Task Parallel Library so I can throw more then one at a time. What are the best practices?
views:
62answers:
3The best approach would be to throw an ArgumentException in each property setter when it's set to an invalid value.
I would say it depends on the property. Another poster recommended ArgumentException, but I feel that this is more specific to invalid arguments passed to a method. I would probably create my own Exceptions (inheriting ApplicationExecption) and make them specific to my properties like:
PropertyNumericRangeException ( numeric property with a range 0-100 lets say)
PropertyStringLengthException ( bounding a string length )
I imagine you could extend AggregateException for this purpose as well, but pretty much sky is the limit here...
Use a validation framework like Enterprise Library Validation Application Block, or you can create your own. Instead of throwing an exception for each validation error report all errors with a single exception.