如何获取事务中止时的错误细节

本文关键字:错误 细节 事务 何获取 获取 | 更新日期: 2023-09-27 18:13:31

我使用System.TransanctionTransanctionCompleted事件来检测终止的事务。

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

如何获取事务中止时的错误细节

你可以在你的事务方法中捕获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);
}