Skip to content

SqlException.Number is always 0 when using .NET framework remoting #1940

Closed

Description

@randbrown

Describe the bug

When using Remoting in .NET Framework, the SqlException.Number getter always returns 0. This makes it difficult to determine the type of SQL error that occurred. In fact, other event details are also missing, such as LineNumber, Class, and so on.

To reproduce

In a remoting client/server context, have the client call the server to insert a duplicate record that violates a unique constraint. On the server, it gets the SqlException with the Number=2627. However, when this exception is passed back to the calling client (over the remoting channel), it comes back with Number=0 (and the other error data is missing)

Expected behavior

Expected behavior is to retain the error number, and other details about the SQL error.

Further technical details

Microsoft.Data.SqlClient version: 5.1.0
.NET target: Framework 4.8, Netstandard2.0
SQL Server version: SQL Server 2019
Operating system: Windows 11

Additional context
I found that in the SqlException class (https://github.com/dotnet/SqlClient/blob/main/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlException.cs), these properties such as Number, LineNumber, etc, get the values from the .Errors collection. I see in the GetObjectData() method it serializes the Errors as null., which would explain why they don't come across the wire. It does, however, put the info into the Data dictionary, so my workaround is to pull the key/value pair from the dictionary to get the error number.

Activity

  1. lcheunglci commented on Mar 3, 2023

    @lcheunglci
    Contributor

    Thanks @randbrown for bringing this issue to our attention. Just to clarify, in a .NET Remoting environment, the SqlException when thrown from the server application to the client application loses the error number/data due the serialization of the SqlException's error collection. We'll have to do some investigation, but if you can provide us with a sample repro application, that would be very helpful.

  2. randbrown commented on Mar 6, 2023

    @randbrown
    Author

    Here is a repro case written as a unit test for the sake of simplicity. The issue can be demonstrated by serialize/deserialize to byte array, which shows the same problem as remoting serialization. Note the Assert() which fails. In this case I'm just pointing out the Number is 0 because that is the main thing affecting my app code, but this issue also causes the Class, LineNumber, Server, etc to be empty.

    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Microsoft.Data.SqlClient;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace MyApp.Common.Tests.DAL
    {
    	[TestClass]
    	public class SqlExceptionTests
    	{
    		[TestMethod]
    		public void TestSqlExceptionSerialization()
    		{
    			using (var conn = new SqlConnection(
    					   "Data Source=(local);Initial Catalog=mydata;Integrated Security=True;User ID=;Password=;Encrypt=No"))
    			{
    				// Try a command which produces an error
    				var command = "insert into NotATable (ID) values ('')";
    				SqlCommand cmd = new SqlCommand(command, conn);
    
    				conn.Open();
    				try
    				{
    					cmd.ExecuteNonQuery();
    				}
    				catch (SqlException exc)
    				{
    					// Invalid object name 'NotATable'
    
    					Assert.AreEqual(208, exc.Number);
    					Assert.AreEqual(1, exc.Errors.Count);
    
    					var bytes = ObjectToByteArray(exc);
    					var excDeserialized = (SqlException)ByteArrayToObject(bytes);
    
    					// Note the deserialized does not have the Errors and thus the Number
    					Assert.AreEqual(0, excDeserialized.Number);
    					Assert.AreEqual(0, excDeserialized.Errors.Count);
    
    					// FAIL because excDeserialized.Number returns 0 
    					Assert.AreEqual(exc.Number, excDeserialized.Number); // FAIL <=============
    				}
    			}
    		}
    
    		public static byte[] ObjectToByteArray(object obj)
    		{
    			BinaryFormatter bf = new BinaryFormatter();
    			using (var ms = new MemoryStream())
    			{
    				bf.Serialize(ms, obj);
    				return ms.ToArray();
    			}
    		}
    
    		public static object ByteArrayToObject(byte[] arrBytes)
    		{
    			using (var memStream = new MemoryStream())
    			{
    				var binForm = new BinaryFormatter();
    				memStream.Write(arrBytes, 0, arrBytes.Length);
    				memStream.Seek(0, SeekOrigin.Begin);
    				var obj = binForm.Deserialize(memStream);
    				return obj;
    			}
    		}
    	}
    }
  3. Wraith2 commented on Apr 18, 2023

    @Wraith2
    Contributor

    I've just tried this and simply adding the error collection into the serialization at the location listed above seems to work.

    Despite the comment:

    si.AddValue("Errors", null); // Not specifying type to enable serialization of null value of non-serializable type

    implying that the SqlErrorCollection is not serializable it is marked as serializable and so is SqlError, so serialization works. I can put up the PR for this single line fix for netfx only.

    This should not be fixed on netcore because binary formatter is deprecated on netcore.

  4. added
    Repro Available ✔️
    on Jan 7, 2026
  5. moved this from To triage to Backlog in SqlClient Boardon Jan 7, 2026
  6. moved this from Backlog to In progress in SqlClient Boardon Sep 2, 2026
  7. priyankatiwari08 commented on Sep 17, 2026

    @priyankatiwari08
    Contributor

    /triage

  8. github-actions commented on Sep 17, 2026

    @github-actions

    🔍 Triage Summary (on-demand re-triage)

    Check Result
    Issue type Bug
    Environment All required environment details provided for investigation (SqlClient 5.1.0, .NET Framework 4.8/Netstandard2.0, SQL Server 2019, Windows 11, repro steps, expected vs actual behavior)
    Area Area\Netfx
    Duplicates None found (an existing linked PR #4622 "Fix
    Regression Not indicated

    Analysis

    SqlException.Number, LineNumber, Class, and other error-detail properties are backed by the Errors collection, but SqlException.GetObjectData() currently serializes Errors as null. This means any cross-AppDomain/remoting or binary-serialization round-trip (e.g. .NET Remoting, BinaryFormatter) silently loses all SQL error details, even though the info is duplicated into the Data dictionary as a workaround. This is a real correctness bug affecting error handling in legacy .NET Framework remoting scenarios; severity is moderate (P2) since it only affects niche binary-serialization/remoting use cases on .NET Framework, and a repro test case plus a proposed one-line fix (serializing Errors for netfx only, since BinaryFormatter is deprecated on .NET Core) have already been supplied by contributors.

    Next Steps

    • Review and progress the existing linked PR Fix | Enable serialization of SqlException #4622, which appears to implement the fix described by contributors (serializing the SqlErrorCollection in GetObjectData() for the .NET Framework path only).
    • If PR Fix | Enable serialization of SqlException #4622 stalls, assign this issue to Copilot coding agent to implement the fix in SqlException.GetObjectData() (guarded with #if NETFRAMEWORK, since BinaryFormatter/legacy serialization is deprecated on .NET/.NET Core) and add a regression unit test mirroring the repro shared in this issue (serialize/deserialize a caught SqlException and assert Number, Errors.Count, LineNumber, Class, and Server are preserved).
    • Ensure any fix maintains backward compatibility and does not affect the netcore/.NET code paths, per the existing contributor guidance.

    Note: This triage summary is auto-generated by an AI agent. The analysis and suggestions above have not been verified by a human maintainer. Please treat as preliminary guidance only.

    Generated by SqlClient Issue Auto-Triage for #1940 · copilot · auto · 51.4 AIC · ⌖ 13.1 AIC · ⊞ 11.9K · ◷

  9. moved this from In progress to Done in SqlClient Boardon Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Repro Available ✔️

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions