SqlException Includes PRINTed Text - Bug?
See original GitHub issueUsing SqlClient, if a SQL statement uses PRINT
to output text then encounters an error, the exception thrown by SqlClient may contain both the error returned by SQL Server (expected) and the output from the print PRINT
statement (not expected).
For obvious reasons, it makes sense that the exception contains the error. 😃 However, the print statement’s contents are not an error and do not necessarily have any connection with the error. Including PRINT
’s output in the exception seems incorrect.
Is this a bug?
Instead, shouldn’t the application subscribe to the connection’s InfoMessage
(ref2) event if they want PRINT
statement output and the exception be limited to just true error message content?
Example
Code
Target Framework: netcoreapp2.2 Package Reference: System.Data.SqlClient, version 4.6.1
using System;
using System.Data.SqlClient;
namespace ErrorExample
{
class Program
{
static void Main(string[] args)
{
using (var connection = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=true")) {
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "PRINT 'hello world!'; THROW 50001, N'Ouch', 1";
command.ExecuteNonQuery();
}
}
}
}
}
Output
System.Data.SqlClient.SqlException: 'Ouch
hello world!'
TDS
At the database protocol-level, the PRINT message is returned in an info token separately from the error message, which is returned in an error token:
-
Info Token - ErrNo: 0, State: 1, Class: 0, Message: 'hello world!', Server Name: [server name]\[instance], ProcName: ''
-
Error Token - ErrNo: 50001, State: 1, Class: 16, Message: 'Ouch', Server Name: [server name]\[instance], ProcName: ''
So, the tokens returned by the server have the two messages properly segmented between them. The problem is client-side, where the two tokens are being aggregated into a single exception.
Issue Analytics
- State:
- Created 4 years ago
- Comments:10 (4 by maintainers)
@bgribaudo I am able to reproduce this with Microsoft.Data.SqlClient as well. We will investigate more into this. Thank you for reporting it!
Thank you, @karinazhou!