how to handle exceptions in a nice way?

One very simple way would be to create a dictionary of ValidationCriterias and corresponding Error Messages for any given class. Since its user input validation checks, I would just throw a valid friendly error message, instead of exception, since such errors were already anticipated.

The following code runs all the validation criterias, even though if any single fails and at the end outputs all the error messages in a pipe separated string. If at least a single criteria fails , the function will return false.

   public class User
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public int Id { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
    }

    public class ValidateProps<T> where T: class
    {
        public static bool RunRules(Dictionary<Expression<Func<T, bool>>, string> lst, 
                                    T myObj, 
                                    out string errorMessages)
        {
            errorMessages = "";
            bool isSuccess = true;
            foreach (var l in lst)
            {
                if (l.Key.Compile()(myObj) == false) isSuccess = false;
                errorMessages += l.Key.Compile()(myObj) == true ? "" : "|" +l.Value;
                
            }
            errorMessages = errorMessages.Trim('|');
            return isSuccess;
        }
    }

    // Example Usage
    User u = new User() { Name = "dd23dd", Age = 100 };
    Dictionary<Expression<Func<User, bool>>, string> dict1 = 
                new Dictionary<Expression<Func<User, bool>>, string>()
                    { {x => Char.IsUpper(x.Name.ToCharArray().ElementAt(0)), "Error Message 1" },
                    {x => !(x.Name.Any(char.IsDigit)), "Error Message 2"},
                    };

     string errorMsgs = "";
     bool n1 = ValidateProps<User>.RunRules(dict1, u, out errorMsgs);

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top