How to Create a SqlException
Join the DZone community and get the full member experience.
Join For FreeHave you tried to create a SqlException only to discover that the constructor is private? Here is how you can create the exception despite of that.
At my current client we are using SQL Server Service Broker (SSB) for messaging. As SSB is based on polling after new messages I have to prevent the log file from getting spammed with the same error message. Especially when the DB fails or when the queue got disabled. So I have to change strategy depending on the returned SQL error code. To do that I was about to let my substitute throw a SqlException with a specific error code.
[TestMethod] public void prevent_insane_polling_if_queue_is_disabled() { var serviceBroker = Substitute.For<IServiceBrokerService>(); var transaction = Substitute.For<IDbTransaction>(); var handler = Substitute.For<IMessageHandler<object>>(); serviceBroker.BeginTransaction().Returns(transaction); serviceBroker.Receive(Arg.Any<RecieveSettings>()).Returns(new[] { new ReceivedMessage { Body = "{}" } }); //this is what I want to be able to do. handler .When(x => x.Handle(Arg.Any<object>())) .Do(x => { throw new SqlException("Queue is disabled", 9617); }); var sut = new SsbReader<object>(serviceBroker, handler); var actual = sut.ProcessMessage(); actual.Should().Be(QueuePollDecision.ExitForAPause); }
However, the only public constructor in SqlException
is the serialization constructor. I opened up the reference source and found the private constructor:
private SqlException(string message, SqlErrorCollection errorCollection, Exception innerException, Guid conId);
Great. Let’s use some reflection to create it. The first thing to do is to get the actual constructor:
var constructor = typeof (SqlException) .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, //visibility null, //binder new[] {typeof (string), typeof (SqlErrorCollection), typeof (Exception), typeof (Guid)}, null); //param modifiers
That was easy. Let’s create the arguments now. The first argument is just the error message. The second should contain the error number that I want:
Ok. Let’s create that class through reflection too:
var collectionConstructor = typeof (SqlErrorCollection) .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, //visibility null, //binder new Type[0], null); var errorCollection = (SqlErrorCollection)collectionConstructor.Invoke(null);
A bit of a hassle, but now we should be able to add our error to the collection, right?
Wrong. The Add() method is also internal. Let’s get it through reflection too:
var addMethod = typeof (SqlErrorCollection).GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance);
Can we please be able to add the error now?
Nope. The SqlError
constructor is internal too. Let’s get it.
var errorConstructor = typeof (SqlError).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof (int), typeof (byte), typeof (byte), typeof (string), typeof(string), typeof (string), typeof (int), typeof (uint) }, null); var error = errorConstructor.Invoke(new object[] {errorNumber, (byte) 0, (byte) 0, "server", "errMsg", "proccedure", 100, (uint) 0}); addMethod.Invoke(errorCollection, new[] {error});
We finally got everything we need to create a SqlException
Here is the full source code:
private SqlException CreateSqlException(int number) { var collectionConstructor = typeof (SqlErrorCollection) .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, //visibility null, //binder new Type[0], null); var addMethod = typeof (SqlErrorCollection).GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance); var errorCollection = (SqlErrorCollection)collectionConstructor.Invoke(null); var errorConstructor = typeof (SqlError).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof (int), typeof (byte), typeof (byte), typeof (string), typeof(string), typeof (string), typeof (int), typeof (uint) }, null); var error = errorConstructor.Invoke(new object[] { number, (byte)0, (byte)0, "server", "errMsg", "proccedure", 100, (uint)0 }); addMethod.Invoke(errorCollection, new[] {error}); var constructor = typeof(SqlException) .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, //visibility null, //binder new[] { typeof(string), typeof(SqlErrorCollection), typeof(Exception), typeof(Guid) }, null); //param modifiers return (SqlException)constructor.Invoke(new object[]{"Error message", errorCollection, new DataException(), Guid.NewGuid()}); }
If you are a class library developer, please be restrictive with the
usage of the internal keyword. In most cases you are protected from
malicious usage through your pipeline. In this case it’s impossible to
inject a SqlException
into the pipeline. i.e. when SqlCommand
throws a SqlException
it can not have come from anywhere else. If it was, it is visible in
the stack trace. So why prevent someone from creating that class?
Published at DZone with permission of Jonas Gauffin, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Unlocking the Power of AIOps: Enhancing DevOps With Intelligent Automation for Optimized IT Operations
-
Competing Consumers With Spring Boot and Hazelcast
-
Mastering Time Series Analysis: Techniques, Models, and Strategies
-
Getting Started With the YugabyteDB Managed REST API
Comments