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 y开发者_运维问答ou 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?
The 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.
If you're using the more recent flavours of .NET, and especially if you're going to be working with WPF/Silverlight, then implementing IDataErrorInfo may be a better solution. Karl Shiflett has written a good article on the pros and cons of throwing exceptions in the property setter versus implementing IDataErrorInfo.
If you have validation rules that are dependent on one or more property values, developers will now have to write code to set property values in a certain order to avoid an exception being thrown. This is a crazy requirement and is contrary all .NET class design documentation. Can you imaging having to wrap EVERY piece of code that sets a property with a try catch block. Again, what about LINQ queries that are tying to populate objects and unnecessary exceptions are being thrown by property setters. This makes writing maintainable code MUCH harder and with ZERO payback. When code is changed over time, a field added, we have to factor in usless exception handling and be cognasent of the order in which property setters are called or change.
精彩评论