所有方法中的异常记录

Sil*_*cer 5 .net c# exception

我们的存储库代码如下所示:

public class PieRepository
{

    public void AddCherryPie(string incredientA)
    {
        try{
            ...
        }
        catch(Exception ex){
            log("Error in AddCherryPie(" + incredientA + ")");
            throw new Exception("Error in AddCherryPie(" + incredientA + ")", ex);
        }
    }

    public void AddApplePie(string incredientA, string incredientB)
    {
        try{
            ...
        }
        catch(Exception ex){
            log("Error in AddApplePie(" + incredientA + "," + incerdientB + ")");
            throw new Exception("Error in AddApplePie(" + incredientA + "," + incredientB ")", ex);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,这try -> catch -> log -> throw new存在于项目中的大多数存储库方法和其他重要方法中。

今天我们对此进行了争论,因为我从未见过有人建议这种类型的错误处理,但主要的论点是我们和支持人员需要确切地知道发生了什么,并且任何其他类型的异常处理都不会给我们确切的信息这...有人能告诉我这是否可以吗?

编辑:抛出错误时添加原始异常消息。

Pet*_*ons 3

切勿创建新的异常。只需使用 throw 重新抛出它,或者至少将原始异常包含为内部异常。否则,堆栈跟踪位于链的更上方,不再正确。它将起源于您所做的地方throw new Exception

更好的是:

public class PieRepository
{
    public void AddCherryPie(string incredientA)
    {
        try{
            ...
        }
        catch(Exception ex){
            log("Error in AddCherryPie(" + incredientA + ")");
            throw
        }
    }
Run Code Online (Sandbox Code Playgroud)

或者

    public void AddApplePie(string incredientA, string incredientB)
    {
        try{
            ...
        }
        catch(Exception ex){
            log("Error in AddApplePie(" + incredientA + "," + incerdientB + ")");
            throw new Exception("Error in AddApplePie(" + incredientA + "," + incredientB ")", ex); // add original exception as inner exception!
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

就我个人而言,我真的建议只使用throw而不是throw new Exception("...", originalException). 通过始终丢弃原始异常,您无法决定流程中稍后要做什么。向用户呈现什么错误?对于数据库错误或验证错误(例如给出消息“数据库不可用”或“未找到成分 A”),操作可能与编程错误不同。

总体方法是有效的。最好尽早记录它,因为这样您就知道方法的参数和错误的上下文。通过重新抛出,您可以通过向用户显示消息或根据异常类型采取其他操作来再次处理 UI 中的错误。

有关错误消息的一些想法,请阅读以下内容:http://blog.ploeh.dk/2014/12/23/exception-messages-are-for-programmers/

现在,如果您确实想对每个方法都执行此操作,请使用面向方面编程(AOP,请参阅https://en.wikipedia.org/wiki/Aspect-oriented_programming)。通过这种技术,您可以使用例如属性来完成此操作。使用 PostSharp 例如: http: //doc.postsharp.net/exception-handling。日志记录不应使代码混乱。