Jim's Software |  Jim and Katrin

Random development notes

Failing a Build

6/15/2008  1:28 PM

Batch files are one of those things I work with so infrequently that I have to research some aspect of them every time.

Today's problem: How do I intentionally fail the build in Visual Studio when my utility program fails?

To bubble an error from a command-line utility, return an error code from the Main() method:

static int Main(string[] args)
{
    int retval = 0;     // success code

    try
    {
        ...
    }
    catch (Exception ex)
    {
        // Return an error code so the caller knows there was a problem
        retval = 1;
        ...
    }
    return retval;
}

If the pre- or postbuild event called the utility directly, you're done; the build will fail.

But if a batch file called it, you need to catch the error in the batch file and bubble it back up:

MyUtility.exe %arg1% %arg2%
:: In case of error, bubble up to visual studio
IF ERRORLEVEL 1 EXIT 1

That link will also explain how to catch different error codes, in case you need the batch file to do more intelligent processing.

It's also possible to mess around with how Visual Studio handles error codes.

Labels:

Comments:

Post a Comment





<< Home