Over a million developers have joined DZone.

How to Create a SqlException

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

Have 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?


Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:

Published at DZone with permission of Jonas Gauffin, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}