异常记录和发送电子邮件

arj*_*jun 3 c# exception-handling

以下异常处理方法是否正确?我发现很难记录错误,最后通过电子邮件发送日志文件.我在哪里编写代码来记录错误并发送电子邮件?

我得到的一个主要问题是,当生成异常SomeClass1时会记录两次 - 第二次来自SomeClass2.创建一个自定义异常类型(SomeException在示例中)并System.Exception在发生时包装它是一个好主意吗?

另外,当我们有一连串的try-catches彼此调用时,我很困惑如何以及何时向最终用户显示错误消息.

class SomeClass1
{
    public static DataExtract(string sourcepath)
    {
        try
        {
            OleDbConnection oledb = new OleDbConnection();
            oledb.ConnectionString = "someconnectionstring";
            CompanyOLEDB.Open();
        }
        catch (Exception e)
        {
            throw new CustomException(e);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
class SomeClass2
{
    private void SomeMethod()
    {
        try
        {
            // some code
            // some code

            SomeClass1.DataExtract()
        }
        catch (Exception e)
        {
            throw new CustomException(e);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
public class CustomException : Exception
{
    protected CustomException() { }

    public CustomException(Exception e)
    {
        Log(e);
    }

    public CustomException(ExceptionType type)
    {
        this.Data.Add("Type", type);
        this.Data.Add("Message", "No message specified");
    }

    public CustomException(ExceptionType type, string message)
    {
        this.Data.Add("Type", type);
        this.Data.Add("Message", message);
    }

    public static void Log(Exception e)
    {
        System.IO.File.WriteAllText(Logfile.txt", e.ToString());
    }

    public static void Sendmail()
    {
        ExceptionMail.Sendmail();
    }
}
Run Code Online (Sandbox Code Playgroud)

jga*_*fin 5

以下异常处理方法是否正确?

不,有几个问题.这是最重要的两个.

你不应该抓住你无法处理的例外情况

非常重要 所有仅重新抛出或记录异常的异常块都会使代码混乱,而不会添加任何值.仅捕获最顶层中的所有异常(在webservice,MVC控制器,后台线程等中)以防止应用程序崩溃.(但是,让应用程序崩溃有时会更好).

如果方法可以返回预期值,则处理异常.

2.始终包含原始例外

当您仅复制原始异常中的部分信息时,您隐藏的信息对于将来能够阻止信息非常重要.

如果你必须抓住/抛出其他你应该这样做:

public class CustomException : Exception
{
    public CustomException(string msg, Exception inner) : base(msg, inner){}
}
Run Code Online (Sandbox Code Playgroud)

//并在一个方法中:

public void DoSomething()
{
    try
    {
        SomeCoolOp();
    }
    catch (Exception err)
    {
        throw new CustomException("Tried to allocate some cool stuff", err);
    }
}
Run Code Online (Sandbox Code Playgroud)

与您的代码相比的变化:

  1. 我们以Microsoft建议的方式包含原始异常
  2. 我们写了一条operation specific消息,即描述异常发生时我们尝试做的事情(而不是使用原始消息)

更多信息

我写了几篇关于异常处理的博客文章.

您可以从阅读开始:http://blog.gauffin.org/2010/11/do-not-catch-that-exception/

而不是阅读其余内容:http://blog.gauffin.org/tag/exceptions/