Skip to content

Instantly share code, notes, and snippets.

@kujotx
Created June 25, 2011 18:12
Show Gist options
  • Save kujotx/1046723 to your computer and use it in GitHub Desktop.
Save kujotx/1046723 to your computer and use it in GitHub Desktop.
xVal RuleException and Extension
/// <summary>
/// Rules Exception
/// </summary>
[Serializable]
public class RulesException : Exception
{
private readonly IList<ErrorInfo> _errors;
public RulesException(string propertyName, string errorMessage)
{
_errors = Errors;
_errors.Add(new ErrorInfo(propertyName, errorMessage));
}
public RulesException(string propertyName, string errorMessage, object onObject)
{
_errors = Errors;
_errors.Add(new ErrorInfo(propertyName, errorMessage, onObject));
}
public RulesException(IList<ErrorInfo> errors)
{
_errors = errors;
}
public IList<ErrorInfo> Errors
{
get
{
return _errors ?? new List<ErrorInfo>();
}
}
}
public class ErrorInfo
{
private readonly string _errorMessage;
private readonly string _propertyName;
private readonly object _onObject;
public ErrorInfo(string propertyName, string errorMessage)
{
_propertyName = propertyName;
_errorMessage = errorMessage;
_onObject = null;
}
public ErrorInfo(string propertyName, string errorMessage, object onObject)
{
_propertyName = propertyName;
_errorMessage = errorMessage;
_onObject = onObject;
}
public string ErrorMessage
{
get
{
return _errorMessage;
}
}
public string PropertyName
{
get
{
return _propertyName;
}
}
}
public static class RulesExceptionExtension
{
public static void AddModelStateErrors(this RulesException ex, ModelStateDictionary modelState, string prefix)
{
foreach (var error in ex.Errors)
{
modelState.AddModelError(error.PropertyName, error.ErrorMessage);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment