处理异常,这是一个好办法?这是一个、好办法、异常

2023-09-02 10:18:06 作者:情依旧

我们正在努力与政策,正确处理异常在我们的应用程序。下面是我们的目标,因为它(总结):

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

只处理特定的异常。 在处理唯一的例外,你可以纠正 在登录一次。

我们已经拿出一个解决方案,它包括一个通用的应用程序特定的异常和工作原理是这样的一块code:

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.