Sunday, November 20, 2005

Setting the DOS ErrorLevel

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/setting_the_dos_errorlevel.htm]

Programs can return an errorLevel. Batch scripts can then access than using %ErrorLevel%, and then use this in the flow of the script. For example, if program X returns a certain errorLevel, the script can take a specific path. Convention is that an errorLevel of 0 is "Success", and anything else is some kind of failure.

This is not to be confused with creating an environmental variable named "ErrorLevel". Setting the environmental variable does not update the batch script's error level itself. This becomes apparent when using another tool that checks the script errorLevel. For example, in NAnt you can execute batch scripts and specify the build to fail if there's an error in the batch. However, you'll notice (at least in version .84) that setting the errorLevel as an environmental variable won't cause the script to fail, but having an exe fail will.

We want the option of setting the errorLevel from an environmental variable, not just through an exe. We can do this by writing a trivial console app:

[STAThread]
static int Main(string[] args)
{
      int i = 0;
      try
      {
         i = Convert.ToInt32(args[0]);
      }
      catch
      {
        Console.WriteLine("Error info...");
      }
      return i;
}

This takes a single argument from the command line, converts it to an integer, and then returns that value as the program error code. Note that console apps need not return "void", as is the template default. They can return int precisely for this purpose.

We can then call this program, passing in some parameter from DOS, and it will set the errorLevel. You'll notice that this would cause the NAnt build to fail. Also note that this call must be the every last line of the batch - not even an ECHO or REM after it.

Confusing the environmental errorLevel and DOS script's errorLevel is an easy and understandable mistake, and fortunately it has an easy and understandable solution.

No comments:

Post a Comment