事务中止时如何获取错误详细信息

时间:2011-11-03 17:07:04

标签: c# transactions

我正在使用System.TransanctionTransanctionCompleted事件来检测已中止的事务。

我如何找出失败的原因?是一种检测错误细节的方法吗?

1 个答案:

答案 0 :(得分:1)

您可以在交易方法上抓住System.Transactions.TransactionException

try
{
    //Create the transaction scope
    using (TransactionScope scope = new TransactionScope())
    {
        //Register for the transaction completed event for the current transaction
        Transaction.Current.TransactionCompleted += new TransactionCompletedEventHandler(Current_TransactionCompleted);
        // proces the transaction
    }

}
catch (System.Transactions.TransactionAbortedException ex)
{
    Console.WriteLine(ex);
}
catch (System.Transactions.TransactionException ex)
{
    Console.WriteLine(ex);
}
catch
{
    Console.WriteLine("Cannot complete transaction");
    throw;
}

交易完成事件处理程序

static void Current_TransactionCompleted(object sender, TransactionEventArgs e)
{
    Console.WriteLine("A transaction has completed:");
    Console.WriteLine("ID:             {0}", e.Transaction.TransactionInformation.LocalIdentifier);
    Console.WriteLine("Distributed ID: {0}", e.Transaction.TransactionInformation.DistributedIdentifier);
    Console.WriteLine("Status:         {0}", e.Transaction.TransactionInformation.Status);
    Console.WriteLine("IsolationLevel: {0}", e.Transaction.IsolationLevel);
}