Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot detect SQL error when using ExecuteNonQuery()

I have the following bit of code which runs a SQL statement:

int rowsEffected = 0;
using (SqlConnection dbConnection = new SqlConnection(dbConnectionString))
{
    try
    {
        dbConnection.InfoMessage += new SqlInfoMessageEventHandler(dbConnection_InfoMessage);
        dbConnection.FireInfoMessageEventOnUserErrors = true;

        dbConnection.Open();


        SqlCommand command = dbConnection.CreateCommand();
        command.CommandTimeout = 0;
        command.CommandText = sqlStatement;

        rowsEffected = command.ExecuteNonQuery();
    }
    catch (Exception e)
    {
        // Handle exception
    }
}

Long running SQL statements can report progress via the SqlInfoMessageEventHandler by raising an error using RAISERROR with the appropriate severity value.

The reasons for setting FireInfoMessageEventOnUserErrors to true is because, without this, all the messages from the SQL statement are only processed all at once when ExecuteNonQuery() returns. With this value set to true, the progress messages are processed as they are raised by the SQL statement.

As the name of the property suggests, the event handler also fires upon errors and not just on the specific severity level reserved for progress feedback by the SQL statement.

The event handler for the progress feedback looks like this:

public void dbConnection_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
    if (e.Errors.Count > 0)
    {
        throw new Exception("Something bad happened");
    }

    // Report progress
}

As you can see, I can detect when an error occurs by the property within 'e' but throwing the exception doesn't do anything. I was hoping execution would drop into the catch block but this isn't the case.

How can I get determine after the ExcecuteNonQuery() method that an error occurred?

TIA

like image 717
millie Avatar asked Mar 15 '12 16:03

millie


2 Answers

I managed to figure a work around. I've added a property to the class that contains the event handler. If there was an error, I sent the error flag property in that class which can then be read following the call to ExcecuteNonQuery(). If there was an error then I can do my clean-up code. Thanks for the reply.

like image 194
millie Avatar answered Oct 19 '22 14:10

millie


Use SqlException class instead of Exception class. And then look into e.Errors

like image 26
Marcin Avatar answered Oct 19 '22 15:10

Marcin