Unable to detect SQL error when using ExecuteNonQuery ()

I have the following bit of code that runs an 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 SQL statements can report progress through the SqlInfoMessageEventHandler, raising an error using RAISERROR with the appropriate severity value.

Reasons to set FireInfoMessageEventOnUserErrors to true, because without it, all messages from the SQL statement are processed only immediately when ExecuteNonQuery () is returned. When this value is set to true, progress messages are processed because they are expressed in an SQL statement.

As the name of the property implies, the event handler also fires when errors occur, and not just at a specific severity level reserved for feedback on the results using the SQL statement.

:

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

    // Report progress
}

, , - 'e', ​​ . , catch, .

ExcecuteNonQuery() ?

+5
2

. , . , , ExcecuteNonQuery(). , . .

+3

SqlException Exception. e.Errors

+1
source

All Articles