2012-07-01 122 views
0

这种方法在我的业务服务中由asp.net mvc控制器调用。 如果发生异常或不需要我需要返回一个Result对象。交易范围内的异常处理

结果类是实验性的,也许有更好的东西。

如果我不希望发生特殊异常,您将如何处理异常。

我只想用一个消息框来显示用户从异常的错误消息,在我的JavaScript文件

如果成功返回false。

public Result CreateTestplan(Testplan testplan) 
{ 
    using (var con = new SqlConnection(_connectionString)) 
    using (var trans = new TransactionScope()) 
    { 
     con.Open(); 

     _testplanDataProvider.AddTestplan(testplan); 
     _testplanDataProvider.CreateTeststepsForTestplan(testplan.Id, testplan.TemplateId); 
     trans.Complete(); 
    } 
    } 

class Result 
{ 
    public bool Success {get;set;} 
    public string Error {get;set;} 
} 

回答

1

裹在Try/Catch块&捕捉异常整个事务。在catch块中将Result上的Error文本设置为例外文本。下面是它的外观在代码:

public Result CreateTestplan(Testplan testplan) 
{ 
    Result res = new Result(); 
    try 
    { 
    using (var con = new SqlConnection(_connectionString)) 
    using (var trans = new TransactionScope()) 
    { 
     con.Open(); 

     _testplanDataProvider.AddTestplan(testplan); 
     _testplanDataProvider.CreateTeststepsForTestplan(testplan.Id, testplan.TemplateId); 
     trans.Complete(); 
     res.Success = true; 
     res.Error = string.Empty; 
    } 
    } 
    catch (Exception e) 
    { 
     res.Success = false; 
     res.Error = e.Message; 
    } 
    return result; 
    } 

class Result 
{ 
    public bool Success {get;set;} 
    public string Error {get;set;} 
} 

当然,你的服务最终会吞噬任何异常,所以你需要确保该交易的失败不处于不一致的状态离开你的程序。

+0

什么不一致的状态可以存在?通常,如果事务失败,所有事情都会回滚。 – Pascal

+0

几乎是正确的,但缺少成功标志真/假 – Steve

+0

@Steve很好的捕获,我做了必要的编辑。 – Chris