处理异常,这是一个好方法吗? [英] Handling exceptions, is this a good way?

查看:29
本文介绍了处理异常,这是一个好方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在努力制定正确处理应用程序异常的策略.这是我们的目标(总结):

We're struggling with a policy to correctly handle exceptions in our application. Here's our goals for it (summarized):

  • 仅处理特定的异常.
  • 只处理可以纠正的异常
  • 只记录一次.

我们提出了一个解决方案,它涉及一个通用的应用程序特定异常,并且在一段代码中是这样工作的:

We've come out with a solution that involves a generic Application Specific Exception and works like this in a piece of code:

try {
  // Do whatever
}
catch(ArgumentNullException ane)
{
  // Handle, optinally log and continue
}
catch(AppSpecificException)
{
  // Rethrow, don't log, don't do anything else
  throw;
}
catch(Exception e)
{
  // Log, encapsulate (so that it won't be logged again) and throw
  Logger.Log("Really bad thing", e.Message, e);
  throw new AppSpecificException(e)
}

记录所有异常,然后将其转换为 AppSpecificException 以便不再记录.最终它将到达最后的事件处理程序,如果需要,它将处理它.

All exception is logged and then turned to an AppSpecificException so that it won't be logged again. Eventually it will reach the last resort event handler that will deal with it if it has to.

我对异常处理模式没有太多经验...这是解决我们目标的好方法吗?它有什么主要缺点或大红色警告吗?

I don't have so much experience with exception handling patterns... Is this a good way to solve our goals? Has it any major drawbacks or big red warnings?

注意: 这样做的一个缺点是,在第一个捕获之后,您将失去处理特定异常的能力(如果您调用一个调用另一个方法的方法,而第二个抛出异常你无法处理它)但我发现我从来没有这样做过......我只处理一个深度级别的异常......

Note: One of the drawbacks of this is that after the first catch you lose the ability to handle an specific exception (if you call a method that calls another method and the second one throws an exception you're not able to handle it) but I've found I've never done this any way ... I only handle exceptions with one level of depth ...

推荐答案

如果您记录异常的时间太接近它第一次抛出的时间,您将不会记录完整的堆栈跟踪.

If you log the exception too near the time it is first thrown, you won't be logging the full stack trace.

处理异常(即修复它们),尽可能接近它们被抛出的时间.尽快收集有关上下文的信息,直到它们被抛出.但允许异常传播到实际可以处理的地方.日志记录是一种最后的处理方式,所以它应该发生在应用子系统的外层.

Handle exceptions (that is, fix them), as close as possible to when they were thrown. Gather information about the context as soon as possible to when they were thrown. But allow exceptions to propagate up to where they can actually be handled. Logging is a last-resort sort of handling, so it should occur in the outer layers of application subsystems.

这应该消除了将特定于应用程序的异常用作标记的需要,以不记录本来不应该被捕获的异常.

This should eliminate the need for an application-specific exception used as a marker to not log an exception which shouldn't have been caught to begin with.

这篇关于处理异常,这是一个好方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆