异常处理的下列方法是否正确?我发现很难记录错误并最终通过电子邮件发送日志文件。 我在哪里编写代码来记录错误并发送电子邮件?异常记录和发送电子邮件
我得到的一个主要问题是,当在SomeClass1
中生成异常时,它会记录两次 - 第二次来自SomeClass2
。创建单个自定义异常类型(示例中为SomeException
)并在发生时包装System.Exception
是否是个好主意?
此外,当我们有一连串的尝试捕获互相调用时,我对如何以及何时向最终用户显示错误消息感到困惑。
class SomeClass1
{
public static DataExtract(string sourcepath)
{
try
{
OleDbConnection oledb = new OleDbConnection();
oledb.ConnectionString = "someconnectionstring";
CompanyOLEDB.Open();
}
catch (Exception e)
{
throw new CustomException(e);
}
}
}
class SomeClass2
{
private void SomeMethod()
{
try
{
// some code
// some code
SomeClass1.DataExtract()
}
catch (Exception e)
{
throw new CustomException(e);
}
}
}
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();
}
}
号见http://msdn.microsoft.com/en-us/library/ms229014.aspx – 2012-03-16 07:10:29
可能重复[Windows窗体应用程序中的异常处理的最佳实践?](http://stackoverflow.com/questions/183589/best-practice-for-exception-handling-in-a-windows-forms-application) – 2012-03-16 07:11:06