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.
CodePudding user response:
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
}
}
}
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.
- An error is caught by T-SQL TRY/CATCH while executing a row-returning statement.
- An error occurs after a row-returning statement successfully executes.
- An error occurs after a row count message is returned (depending on client API).
See this article for more details.