How to properly return error message from Console to SQL Server Agent

3.2k views Asked by At

I have a C# Console application that will be run from SQL Server agent. If the console application fail, i would like to have the error message shown in the SQL Server agent history log. But it doesnt seem to grab anything from the console app. It only says:

Message Executed as user: domain\account. The step did not generate any output. Process Exit Code 1. The step failed.

So how should i built my console application so that the SQL Server agent would print the error message instead of the "The step did not generate any output." message?

Here's a simple code that i have tested:

class Program
{
    static void Main(string[] args)
    {
        var x = 0;

        // division by zero error
        var y = 1 / x;


        //Console.Error.WriteLine("error message");
    }
}
1

There are 1 answers

0
Alexandre Jobin On BEST ANSWER

As stated by @ChrisK, to correctly build a Console Application that will return an error message to SQL Server Agent, the code must use a try/catch and write the error message to the Console.Error

Writing the code that way solved my problem:

static int Main(string[] args)
{
    try
    {
        var x = 0;
        var y = 1 / x;
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex);
        return 1;
    }

    return 0;
}