none
Best practice for Validation that also returns error messages? RRS feed

  • Question

  • Dear All,

    Error handling for C# is by 

    try

    {

    ...

    }

    catch (Exception e)

    {

    ....

    }

    In most case for our functions, we need to validate the result, and return SUCCESS and FAILURE.

    When FAILURE occurs, sometimes we want to shows the error msg to user,

    What is the best practice for c# platform or architecture?

    Is the following way adopted by Microsoft? 

    https://codereview.stackexchange.com/questions/135945/validation-that-also-returns-error-messages

    Thanks and Best regards

    E-John


    • Edited by E-John Tuesday, December 4, 2018 5:56 AM
    Tuesday, December 4, 2018 2:32 AM

Answers

  • Myself, I use a List<string> call it Errors. A validation error is placed in the Errors collection. I check for Errors,count > 0, and if Errors.count > 0, then I display the validation error message or messages to the user.

    I create a new Errors collection at the start of the validation process. To me having a bunch try/catches all over the code for validation errors is questionable. Also, you have 20 validations using a try/catch for each one  terminates any further validation in the rest of the validation process so that the user only sees one validation error message at a time,  if say the user has 5 validation errors, the user sees each validation error one at a time as they validate instead of seeing all 5 validation messages at the end of the validation process. 

    You send the Errors collection to an Error form to a grid or something and show all the errors messages to that point, which is a lot more user friendly, instead of user pushes the Save button and gets a validation error, the user corrects the error, user pushes the button again, there is a different  error message and the user has to push the button and correct error 5 times to get all 5 errors.


    • Edited by DA924x Tuesday, December 4, 2018 6:30 AM
    • Marked as answer by E-John Thursday, March 28, 2019 1:33 AM
    Tuesday, December 4, 2018 6:27 AM

All replies

  • Myself, I use a List<string> call it Errors. A validation error is placed in the Errors collection. I check for Errors,count > 0, and if Errors.count > 0, then I display the validation error message or messages to the user.

    I create a new Errors collection at the start of the validation process. To me having a bunch try/catches all over the code for validation errors is questionable. Also, you have 20 validations using a try/catch for each one  terminates any further validation in the rest of the validation process so that the user only sees one validation error message at a time,  if say the user has 5 validation errors, the user sees each validation error one at a time as they validate instead of seeing all 5 validation messages at the end of the validation process. 

    You send the Errors collection to an Error form to a grid or something and show all the errors messages to that point, which is a lot more user friendly, instead of user pushes the Save button and gets a validation error, the user corrects the error, user pushes the button again, there is a different  error message and the user has to push the button and correct error 5 times to get all 5 errors.


    • Edited by DA924x Tuesday, December 4, 2018 6:30 AM
    • Marked as answer by E-John Thursday, March 28, 2019 1:33 AM
    Tuesday, December 4, 2018 6:27 AM
  • Hi E-John,

    Thank you for posting here.

    For your question, you want to look for best practice for c# platform or architecture.

    If your program has 10 lines of code, but only uses one try catch, but the third line and the fifth line prompt an error, the program will stop on the third line, and will not execute the fifth line error.

    As I know, this mechanism could not be implemented, because when the statement uses the try catch statement, it will stop when it encounters an error.

    Best regards,
    Jack J Jun.


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, December 5, 2018 8:25 AM
    Moderator
  • Dear All,

    Error handling for C# is by 

    try

    {

    ...

    }

    catch (Exception e)

    {

    ....

    }

    In most case for our functions, we need to validate the result, and return SUCCESS and FAILURE.

    When FAILURE occurs, sometimes we want to shows the error msg to user,

    What is the best practice for c# platform or architecture?

    Is the following way adopted by Microsoft? 

    https://codereview.stackexchange.com/questions/135945/validation-that-also-returns-error-messages

    Thanks and Best regards

    E-John


    It's ridiculously simple.

    For instance, suppose a type named SomeType  that should be considered invalid if its property named S (of type string) is either null or empty:

    public class SomeType
    {
      public string S{get;set;}
      public static bool TryValidate(SomeType st,out string msg)
      {
        if(string.IsNullOrEmpty(st.S))
        {
          msg=st.S==null?"Invalid: property is null.":"Invalid: property is empty";
          return false; // not valid
        }
        msg=string.Empty;
        return true; // valid
      }
    }
    

    and you can test it this way:

    SomeType a=new SomeType{S=""};
    bool valid=SomeType.TryValidate(a,out var msg);
    Console.WriteLine($"object is {(valid?"valid":msg)}");
    

    Thursday, December 6, 2018 12:00 AM
  • Hi DA924x,

    I think I got your point, it is something like the snippet below,

    If there is file name list to be validated, use List<string> errMsg we could get all invalid cases of the data be validated.

    Thanks for your helps.

    Best regards,

    E-John

        public class Validater
        {
            public static List<string> FileNames(List<string> fileNameList, string titleString)
            {
                List<string> errMsg = new List<string>();
                errMsg.Clear();
    
                // can not be empty
                foreach (string fileName in fileNameList)
                {
                    if (string.IsNullOrEmpty(fileName) == true)
                    {
                        errMsg.Add("MsgFileNameIsEmpty");
                    }
                }
    
                List<string> duplicatedFileNameList = new List<string>();
                duplicatedFileNameList.Clear();
    
                if (fileNameList.Count != 0)
                {
                    var query = fileNameList.GroupBy(x => x)
                                            .Where(g => g.Count() > 1)
                                            .Select(y => y.Key)
                                            .ToList();
    
                    // name can not be duplicated
                    if (query.Count != 0)
                    {
                        errMsg.Add("MsgFileNameIsDuplicate");
                    }
                }
    
                if (errMsg.Count != 0)
                {
                    string msgStr = null;
                    foreach (string s in errMsg)
                    {
                        msgStr += GetTranslatedMsgBoxString(s) + "\r\n" + "\r\n";
                    }
    
                    MessageBox.Show(msgStr,
                                    titleString,
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);
                }
    
                return errMsg;
            }
        }



    • Edited by E-John Thursday, March 28, 2019 1:37 AM
    Thursday, March 28, 2019 1:32 AM