如何处理代码深处的异常?

时间:2011-09-06 23:35:04

标签: c# exception exception-handling error-handling

我有一个返回xml的web服务。问题是在代码中“深入”执行的方法,其中简单的返回不会停止程序执行。

我在catch语句中设置了我的xml错误消息,但代码将继续执行外部方法的其余部分并覆盖我的xml错误响应。

是否有设计模式或最佳实践来解决这个问题?

      Main Program Block                    SomeClass

         execute someMethod()     ---->     public someMethod()
                                            {
                                                    -----> private method()// try / catch error occurred (send back an xml error response)

                                                    // code execution continues and does some stuff and generates an xml response
                                                    <request>
                                                    <success>true</success>
                                                    </request>
                                            }

5 个答案:

答案 0 :(得分:4)

catch (Exception)
{
    // Set errors here
    throw;
}

这将重新抛出异常。这就是你要找的东西吗?

答案 1 :(得分:3)

您可以重新抛出异常。例如:

    private static string errorMessage;
    static void Main(string[] args)
    {
        try
        {
            Test1();
        }
        catch (Exception ex) 
        {
            Console.WriteLine("Something went wrong deep in the bowels of this application! " + errorMessage );
        }

    }

    static void Test1()
    {
        try
        {
            Test2(1);
            Test2(0);   
        }
        catch (Exception ex)
        {
            errorMessage = ex.Message;
            throw;
        }
    }

    static string Test2(int x)
    {
        if (x==0) throw new ArgumentException("X is 0!");
        return x.ToString();
    }

另外一条建议:重新抛出异常时,请使用throw;,而不是throw ex;,以保留堆栈跟踪。有关此主题的更多信息,请参阅this

答案 2 :(得分:3)

您需要考虑在架构中设置异常边界。

我过去成功使用Microsoft's Exception Handling Block来做到这一点。

这将允许您设置不同的策略来处理和传播异常,如下图所示;

它可以帮助您处理scenarios,例如;

  • 记录
  • 更换
  • 包装
  • 宣传
  • 用户友好留言

enter image description here

值得一看,这取决于你想要进行异常处理的程度。

答案 3 :(得分:1)

通常明智的做法是尽可能地捕捉你的例外情况。因此,主要的服务方法是负责捕获不同类型的异常并确定适当的响应。深入代码不应该只是“吞下”异常,除非它真的知道如何处理它并优雅地继续前进。

如果你想这样做,某些异常可以告诉上层代码它应该使用响应的特定信息,你可以创建一个自定义异常类型,其属性是服务方法中的异常捕获代码可以检查。

// In your deep down code
catch (Exception e)
{
    throw new ReturnErrorMessageException("The user should see this message.", e);
}
// In your service method
catch (SendErrorMessageException e)
{
    Response.Message = e.UserFacingErrorMessage;
    _logger.LogError("An error occurred in the web service...", e);
}

答案 4 :(得分:0)

您正在寻找的最佳解决方案可能是使用面向方面编程(AOP)并创建一个异常处理方面,捕获并处理所有异常,然后检查服务级别的异常。

这样做的好处是它可以从代码中删除try catch,并使您能够以模块化方式处理异常。

.NET的一些AOP解决方案包括Castle Windsor,Spring.NET和Microsoft Unity。

相关问题