DCSIMG
Debugging Distributed Transactions: Fault Handling - All Your Base Are Belong To Us

All Your Base Are Belong To Us

Mostly .NET internals and other kinds of gory details

Debugging Distributed Transactions: Fault Handling

How is a WCF service call under a distributed transaction different from a regular WCF service call? The primary difference is the transactional abort semantics in case of failure.

If the WCF service operation fails when there is no ambient transaction, the failure can be contained—the service caller may decide to ignore the error and proceed. However, if the WCF service operation fails within a distributed transaction, the transaction’s abort flag is set (by default), so that the caller cannot proceed with the transaction. In other words, if you handle a fault from a transactional WCF service and want to swallow the error and continue working, you will need a new transaction—the old transaction will have already been aborted.

This mistake (that stems from the fact the transaction is automatically aborted) is demonstrated by the following failing test:

[TestMethod]
public void ExceptionHandledWhenServiceFails()
{
    IBookStore store = ObtainBookstore();
    using (TransactionScope tx = new TransactionScope())
    {
        try
        {
            store.PromoteCustomerToVIP("@$!$!@#!");
            Assert.Fail("Exception expected.");
        }
        catch (FaultException)
        {
        }
        tx.Complete();
    }
}

The problem here is that because the transaction has already been aborted, the tx.Complete() call will throw an exception. Here’s the right way to write this test:

[TestMethod]
public void ExceptionHandledWhenServiceFails_Right()
{
    IBookStore store = ObtainBookstore();
    try
    {
        using (TransactionScope tx = new TransactionScope())
        {
            store.PromoteCustomerToVIP("@$!$!@#!");
            tx.Complete();
        }
        Assert.Fail("Exception expected.");
    }
    catch (FaultException)
    {
    }
}

In the next installment, we’ll start looking at transactional deadlocks—the plague of distributed transactions.

Comments

No Comments

Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: