問題描述
我們正在努力制定正確處理應(yīng)用程序異常的策略.這是我們的目標(biāo)(總結(jié)):
We're struggling with a policy to correctly handle exceptions in our application. Here's our goals for it (summarized):
- 只處理特定的例外情況.
- 只處理您可以糾正的異常情況
- 只記錄一次.
我們提出了一個涉及通用應(yīng)用程序特定異常的解決方案,并在一段代碼中像這樣工作:
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)
}
記錄所有異常,然后將其轉(zhuǎn)換為 AppSpecificException,這樣就不會再次記錄它.最終它將到達(dá)最后的事件處理程序,如果它必須處理它.
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.
我對異常處理模式?jīng)]有太多經(jīng)驗(yàn)...這是解決我們目標(biāo)的好方法嗎?它有什么主要缺點(diǎn)或大紅色警告嗎?
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?
注意:這樣做的一個缺點(diǎn)是,在第一次 catch 之后,您將失去處理特定異常的能力(如果您調(diào)用的方法調(diào)用了另一個方法,而第二個方法拋出了異常你無法處理它)但我發(fā)現(xiàn)我從來沒有這樣做過......我只處理一個深度級別的異常......
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.
處理異常(即修復(fù)它們),盡可能接近它們被拋出的時間.盡快收集有關(guān)上下文的信息,直到它們被拋出.但是允許異常傳播到可以實(shí)際處理的地方.日志記錄是最后的處理方式,因此它應(yīng)該發(fā)生在應(yīng)用程序子系統(tǒng)的外層.
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.
這應(yīng)該消除了使用特定于應(yīng)用程序的異常作為標(biāo)記的需要,以不記錄一開始就不應(yīng)該被捕獲的異常.
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.
這篇關(guān)于處理異常,這是個好辦法嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!