簡體   English   中英

可重用的嘗試/捕獲塊

[英]Reusable Try/Catch Block

我寫了以下方法,認為它可以讓我傳遞一個方法調用以包裝在try catch中。 我試圖避免在整個應用程序中放置相同的try / catch樣板代碼。 我已經有20多個電話,到完成時,將有數百個電話。

protected T CallRepository<T>(T repositoryMethod)
{
    try
    {
        return repositoryMethod;
    }
    catch (Exception ex)
    {
        logger.Error(ex);
        throw new DatabaseException();
    }
}

調用方法如下:

var results = CallRepository<VisitLogDTO>(visitLogRepository.AddVisit(visitLogDTO));

起初我沒有意識到這沒有按預期進行。 發生的結果是將結果包裝在try / catch中,而不是包裝在方法的調用中。 如果我從visitLogRepository得到數據庫錯誤或任何錯誤,那么我就是原始錯誤,而不是新的DatabaseExeception。

任何幫助將不勝感激。

您需要傳遞Func<T>而不是T

protected T CallRepository<T>(Func<T> repositoryMethod)
{
    try
    {
        return repositoryMethod();
    }
    catch (Exception ex)
    {
        logger.Error(ex);
        throw;
    }
}

並像這樣使用它:

var results = CallRepository(() => visitLogRepository.AddVisit(visitLogDTO));

我不確定,但似乎AddVisit方法是在CallRepository方法之外調用的。 嘗試將動作委托用作方法參數,然后在方法中調用該委托,以確保在try catch中完成了該調用。 然后使用Lambda表達式進行調用:

private handleException(Action myAction)
{
    try
    {
        myAction();
    }
    catch[...]
}

呼叫:

 handleException( () => { int result = FunctionThatThrowsException(); } )

最好的Lumo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM