1

I have a simple C# console application that talks to a webservice. I am not sure if the way I am handling expections and returning error codes are proper. Would like to have comments on good pratice to do this. (I am using CommandLine.dll for option parsing)

class Program
    {
        static int Main(string[] args) {
            var options = new Options();
            if (CommandLine.Parser.Default.ParseArguments(args, options)) {
                try {
                    var client = new MyWebService();
                    var response = client.MyFunction(new MyRequest() { Param1 = options.param1, Param2 = options.Param2 });
                    if (response.ErrorCode != 0) {
                        Console.WriteLine("Error code= " + response.ErrorCode);
                    }
                    else {
                        File.WriteAllText(options.OutputFile, response.File);
                        return 0;
                    }
                }
                catch (Exception exp) {
                    Console.WriteLine(exp.Message);
                    return 1;
                }
            }
            return 1;
        }
    }
softwarematter
  • 28,015
  • 64
  • 169
  • 263

2 Answers2

1

You should use the Console.Error.* to write errors. And I'll say that this:

if (response.ErrorCode != 0) {
    Console.Error.WriteLine("Error code= " + response.ErrorCode);
    return 1;
} else {
    File.WriteAllText(options.OutputFile, response.File);
}

plus a final

return 0;

after the catch would be better, so that if you have multi-stage operations to do, it's easier to code (fall-through == ok, error == fast abort)

with multi-stage I mean:

call ws1
check for non-Exception errors of ws1, if errors abort
call ws2
check for non-Exception errors of ws2, if errors abort
call ws3
check for non-Exception errors of ws3, if errors abort
return success

In the cmd prompt, to save errors:

myprogram 2>err.txt

to redirect output + error:

myprogram > err.txt 2>&1

(the last one was taken from https://stackoverflow.com/a/1420981/613130)

Last thing: if the parsing of the arguments goes wrong, you should output an error.

Community
  • 1
  • 1
xanatos
  • 109,618
  • 12
  • 197
  • 280
-1

You should refactor the MyWebService class and the MyFunction to throw exceptions if an error occurs. Instead of returning error codes. That gives you full flexibility in terms of who at which level can handle the errors and it makes the code much more readable.

meilke
  • 3,280
  • 1
  • 15
  • 31