0

我有一种方法,A)在表中插入一行,然后 B)在另一个表中的多个插入中使用生成的 Identity 值。如果 B 部分中的逻辑由于任何原因失败,我需要回滚 B 和 A 部分的所有插入。我相当肯定事务不会为此工作,尽管我愿意接受其他方式的说服。我有一个“主要”方法来处理对执行 A 和 B 的方法的调用,这些方法被 try-catch 包围。我想知道的是,如果我从主方法的catch中调用一个执行回滚功能的方法,并且回滚方法中出现故障,回滚方法中捕获的异常(我想记录它)是否会清除堆栈跟踪(或其他)主要方法中捕获的异常?代码示例:

public class DoSomeStuff
{
    public void MainMethod(...)
    {
         int identity;
         try
         {
              identity = DoFirstInsert(...);
              DoSubsequentInserts(identity, ....);
         }
         catch
         {
              RollbackStuff(identity);
              throw;
         }
    }

    void RollbackStuff(int identity)
    {
         try
         {
              //Do database stuff to rollback inserts
         }
         catch(exception ex)
         {
              //Log rollback error, DO NOT THROW
              //Will this wipe out the exception caught in MainMethod()?
         }
    }
}

提前致谢。

4

2 回答 2

3

交易应该有效。将所有插入包装在一个事务中,包括返回标识列的插入。

于 2009-07-27T15:24:44.333 回答
1

不,例外不会被消除。我创建了一个控制台应用程序来测试它:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();

            try
            {
                p.MainMethod();
            }
            catch (Exception ex)
            {
                Console.WriteLine("=== Insert Exception ===");
                Console.WriteLine(ex.ToString());
                Console.WriteLine();
            }

            Console.ReadLine();
        }

        public void MainMethod()
        {
            int identity = 0;
            try
            {
                identity = DoFirstInsert();
                DoSubsequentInsert(identity);
            }
            catch
            {
                RollbackStuff(identity);
                throw;
            }
        }

        private void RollbackStuff(int identity)
        {
            try
            {
                throw new Exception("Exception on rollback");
            }
            catch (Exception ex)
            {
                Console.WriteLine("=== Rollback Exception===");
                Console.WriteLine(ex.ToString());
                Console.WriteLine();
            }
        }

        private void DoSubsequentInsert(int identity)
        {
            throw new Exception("Exception on insert");
        }

        private int DoFirstInsert()
        {
            return 1;
        }
    }
}

于 2009-07-27T15:36:38.133 回答