简体   繁体   中英

Can I dynamically check a case statement of a switch in c#?

Today I came across a problem: I was trying to check the errors of a software in order to provide the right behavior of the program when it incurs in the error.

I had to check if a user already exists in the database.

The problem is that the back-end doesn't provide an errorId so I have to check the errors by the text.

Errors are displayed as this:

The user Name already Exists!

The Switch statement is this:

switch (error.text)
{ 
  case "User Test already exists":
    Console.WriteLine("The user already Exists"); //this is a test behaviour. 
    break;
  default:
    Console.WriteLine("I couldn't behave in any way :<");
}

As you can imagine the names are all different (it's a unique field in the DB), so the word "Test" in the case statement should be the name of the user.

Can I dynamically change the string?

Seems like a Regex would do the trick. I've built this Regex based off the pattern:

The user Name already Exists!

where Name can be any value. The Regex is:

(the user .* already exists)

To use it you'll do something like this:

Regex.IsMatch(error.text, "(the user .* already exists)", RegexOptions.IgnoreCase)

Which would return a true or false based on the match. Now, this can't be done in the switch, but you could just run the value through a number of Regexes to determine which it matched. One thing you might consider is an extension method. Consider this one:

public static class RegexExtensions
{
    private static readonly Regex UserNameAlreadyExists = new Regex("(the user .* already exists)", RegexOptions.IgnoreCase | RegexOptions.Compiled);

    public static bool IsUserNameAlreadyExists(this string inputValue)
    {
        return UserNameAlreadyExists.IsMatch(inputValue);
    }
}

The usage for this would be really nice:

if (error.text.IsUserNameAlreadyExists())
{
    // do something
}

The extension method is a really nice way of working through it. It's fully encapsulated and would keep the usage really clean. Furthermore, it's easier to define the Regex in one place and thus set it to Compiled making it faster.

Preferably change the back-end or have it changed (it definitely should return some sort of error code instead of an already localized message obviously meant to be shown to the user - that's clearly a front-end task).

To answer the question, no; consider using something like this instead (original phrasing, be aware that these string comparisons are case sensitive):

if(error.text.StartsWith("User ") && error.text.EndsWith(" already Exists"))
{ 
    Console.WriteLine("The user already Exists"); //this is a test behaviour. 
}
else
{
    Console.WriteLine("I couldn't behave in any way :<");
}

I suppose this would be a fairly simple solution:

class Program
{

    int errorIndex = 5; //Based on error expected text. Can add more criteria here.

    private static bool testResponse = false;

    static void Main(string[] args)
    {
        string text = "The user already exists";


        getErrorMessage(text);

    }


    private static void getErrorMessage(string message)
    {

        var user = message.Substring(4, 4);
        var exists = message.Substring(17, 6);
        if (user == "user" && exists == "exists")
            //Write the error message.
            Console.WriteLine(message.ToString());
            var errorMessage = message;
            if (errorMessage != null)
            {
                testResponse = true;
            }
            Console.ReadLine();



    }
}

This is if you know the exact location of the length and index of certain words of the error message. You could use that information to further narrow down the errors you expect. This is assuming that there is no errorId.

just to be sure: The back-end doesn't provide any errorID? If you use C# for the database connection (ie ADO.Net) you have possibilitys for efficent error handling.

Is it possible to just check if error.text is empty or not?

if(error.text=="")Console.WriteLine("The User already exists");
else Console.WriteLine("I couldn't behave in any way");

If you want to check if there are duplicates in the "user" column you could check the database directly via SQL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM