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

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

问题描述

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

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?

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

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天全站免登陆