DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

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

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
  1. DZone
  2. Data Engineering
  3. Databases
  4. How to Create a SqlException

How to Create a SqlException

Jonas Gauffin user avatar by
Jonas Gauffin
·
Aug. 26, 14 · Interview
Like (0)
Save
Tweet
Share
5.23K Views

Join the DZone community and get the full member experience.

Join For Free

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?


Pipeline (software) sql Serialization dev IT Library Polling (computer science)

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

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: