问题描述:

I have developed a server that accepts connections from clients (using TCP/IP) for operations with different providers. Server performs operations and return back output to client.

My server has to send back error codes in case of errors during flow and client should know where exactly error has occurred.

For Example, If server is not able to connect with provider, client should get back ERROR CODE 107 and DESCRIPTION "CONNECTION ERROR WITH PROVIDER".

What is the best way to save error codes on server instead of hard coding them in code?

网友答案:

If you made that "server" from scratch ( means that you're using pure socket or TcpClient ). I would recommend you to make some kind of .ini file that contains key value pair like :

107=CONNECTION ERROR WITH PROVIDER

To read this you can use this snippet :

public Dictionary<int, string> ReadIniFile(string filePath)
{
    Dictionary<int, string> result = new Dictionary<int, string>();
    using ( StreamReader reader = new StreamReader(new FileStream(filePath, FileMode.Open))
    {
        string line = string.Empty;
        while( ( line = reader.ReadLine() ) != null )
        {
            if(line.Contains('='))
            {
                int eCode = 0;
                if( int.TryParse(line.Split('=')[0], out eCode) )
                {
                    result.Add(eCode, line.Split('=')[1]);
                }
            }
        }
    }
    return result;
}

Doing this you can implement FileWatcher and whenever your .ini file is modified, you can re-run this method to gather new codes or you can just read all of the error codes into Dictionary<int, stirng> when application/server initialzies or even just read desired value when error occures.

Another way is ( as you wrote in the question ) to hardcode error codes into the application source :

Dictionary<int, string> error_codes = new Dictionary<int, string>();
error_codes.add(107, "CONNECTION ERROR WITH PROVIDER");

Which will require rebuild for every new error code ( inefficient as ... hell ).

Yet another possibility is to use server.exe.config file in which you can store error codes with description ( which can or cannot require rebuild ).

相关阅读:
Top