简体   繁体   中英

Catch an error from try/catch in SQL Server at client side (C# Winform) using ExecuteScalar

I am developing windows application in C# with SQL Server as backend. I have to display the error message generated in stored procedure, which is handled in try catch block, to the application. It is working fine if we use ExecuteNonQuery() . The stored procedure will return one ID so I am using ExecuteScalar() and that error message from the catch block is not displaying.

For ExecuteScalar also the error will display if we remove the try catch block.

It will not display in client side.

begin
begin try
    select 1/0
    select 10
end try
begin catch
    raiserror (' Some Error Message', 16, 10)
end catch
end

It will display in client side.

begin
    select 1/0
    raiserror (' Some Error Message', 16, 10)
    select 10
end

Kindly provide a solution.

In order to ensure SqlExceptions are detected, all result sets must be consumed by the client. ExecuteScalar() returns only the first row/column of the result but does not consume the remainder of the results, so the exception is not raised by the client API.

This example code will raise the error by avoiding ExecuteScalar() and consuming all results:

try
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    using (SqlCommand command = new SqlCommand(sqlBatchText, connection))
    {
        connection.Open();
        using (SqlDataReader reader = command.ExecuteReader())
        {
        if (reader.Read())
            {
                scalarIntResult = reader.GetInt32(0);
        }
        while (reader.Read()) { }; //consume remainder of first result
        while (reader.NextResult()) { }; //consume subsequent results
        }
        Console.WriteLine("{0} rows read", rowCount);
    }
}
catch
{
    throw;
}

Below are common cases where undetected SqlExceptions may occur. If a defensive programming technique like the above is not employed, it is important to code T-SQL to ensure these scenarios do not occur.

  1. An error is caught by T-SQL TRY/CATCH while executing a row-returning statement.
  2. An error occurs after a row-returning statement successfully executes.
  3. An error occurs after a row count message is returned (depending on client API).

See this article for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM