views:

62

answers:

3

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?

+3  A: 

The best approach would be to throw an ArgumentException in each property setter when it's set to an invalid value.

David Stratton
A: 

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...

James Connell
See http://stackoverflow.com/questions/52753/should-i-derive-custom-exceptions-from-exception-or-applicationexception-in-net for best practice on what to derive from.
Hightechrider
If I use this approach as an "enduser" I'd have to check the exception type and if I want to pass along a validation error message to a client then I've got to write a bunch of logic to line up the ui field and the exception message. What are your recommendations for handling that kind of logic?
K-Bell
I think as an enduser, I would want to check for specific types of exceptions, and handle them accordingly. That is the whole reason for making them specific, anybody can just catch Exception and display the message, but sometimes you want to handle certain exceptions differently. As for displaying messages in the UI, this is really up to you and your interface design. Perhaps just outline the input in red and display a dialog with the error, or show the errors in a list at the top (there are many ways to handle it)
James Connell
A: 

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.

Max Toro