Search code examples
c#.netvalidationpropagation

What are good/standard ways to propagate data integrity validation errors to the user?


I am developing a data-driven web application using ASP.Net MVC 3. I will be using NHibernate for data access, but my question is language agnostic (applies to all languages which have the exception concept).

I have come to the conclusion that I better enforce my data integrity rules both in the actual database and in the repository implementation to retrieve said data, for security and edge cases where the offered integrity mechanisms is not flexible enough.

Question

I am thinking I should probably encapsulate said validation inside my IRepository implementations. Using for example a custom MVC validation attribute to query the database for validation sits unnatural in my mind; such processing seems better left for somewhere else.

If I perform my validation in the IRepository implementations, how should I propagate it to the calling context?

I see a few options:

  • Subclassing Exception with something like ValidationException (or if it already exists). Provide the USER FRIENDLY message as the Message property.

The above is easy to implement, but it assumes that the calling context wants to display text to the user. It also makes it hard for the calling context to provide localization (something I believe has no place in an exception - I hate attempting to translate before googling!).

  • Same as above, but instead of a text message provide ValidationException<ValidationEnum>, where ValidationEnum is an Enum which describes the error for the subject model.

This allows the calling context full freedom in interpreting the error. I am leaning towards this method, even though it contaminates the code with a huge amount of enum values.

Are there any other options than these that are more beautiful?


Solution

  • Depending on the architecture, implementing IDataErrorInfo on your domain types might be an option; this allows you to indicate failure at both the object and object+member level, and IIRC this is now also handled automatically by MVC (a number of other frameworks such as winforms etc have supported this for ages).