[英]Good practice design pattern for Exception handling
我在底層方法的下面代碼的每個方法中都有異常處理代碼
throw new Exception("The error that happens");
有什么辦法可以避免在每種方法中一次又一次地編寫這段代碼嗎?
我正在嘗試編寫自己的代碼而不使用任何日志框架
private void TopLevelMethod()
{
try
{
SomeMethod();
}
catch (Exception ex)
{
// Log/report exception/display to user etc.
}
}
private void SomeMethod()
{
TestPartA();
TestPartB();
TestPartC();
TestPartD();
}
private void TestPartA()
{
// Do some testing...
try
{
if (somethingBadHappens)
{
throw new Exception("The error that happens");
}
}
catch (Exception)
{
// Cleanup here. If no cleanup is possible,
// do not catch the exception here, i.e.,
// try...catch would not be necessary in this method.
// Re-throw the original exception.
throw;
}
}
private void TestPartB()
{
// No need for try...catch because we can't do any cleanup for this method.
if (somethingshappens)
{
throw new Exception("The error that happens");
}
}
如果你想對他們做一些有意義的事情,只捕捉錯誤,例如:
SqlException
永遠不會傳遞給你的套接字級錯誤。它會傳遞一個有意義的SQL錯誤代碼) 記錄幾乎從不合適。 頂級處理程序應該記錄。 當然不是路徑中的每個方法都應該記錄。 日志和代碼是多么混亂。 不要那樣做。
只是不要吞下錯誤信息,讓錯誤消失。 這樣就沒有理由在任何地方插入本地日志記錄代碼來處理錯誤。
如果您更喜歡使用類似代碼風格的函數式編程,一種方法是使用回調錯誤回調。 示例:
private void SomeMethod()
{
// do something
}
public bool Execute(Action act, Action<Exception> onErrorCallback)
{
var res = true;
try
{
act();
}
catch (Exception ex)
{
res = false;
onErrorCallback(ex);
}
return res;
}
並像這樣使用Execute
:
var successfull = true;
successfull &= Execute(SomeMethod, (ex) => { /* clean up */ });
successfull &= Execute(SomeMethod, (ex) => { /* clean up */ });
successfull &= Execute(SomeMethod, (ex) => { /* clean up */ });
successfull &= Execute(SomeMethod, (ex) => { /* clean up */ });
if (!successfull)
; // show user or something else
Graffito:請你舉個示例代碼示例.Thankyou ......
您的代碼重構:
private void TopLevelMethod()
{
List<string> errors=new List<string>() ;
if (!SomeMethod(errors)) { /* Log/report errors/display to user etc. */ }
}
private bool SomeMethod(List<string> errors)
{
return TestPartA(errors) && TestPartB(errors) && TestPartC(errors) && TestPartD(errors);
}
private bool TestPartA(List<string> errors)
{
bool result = true ;
try
{
// Do some testing...
if (somethingBadHappens) { result=false; errors.Add("The error that happens"); }
}
catch (Exception ex) { errors.Add("Error in TestPartA: "+Ex.Exception.Message.ToString()) ; }
return result ;
}
private bool TestPartB(List<string> errors)
{
bool result = true ;
// Do some testing...
if (somethingBadHappens) { result = false ; errors.Add("The error that happens"); }
return result ;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.