【发布时间】:2012-03-16 06:59:25
【问题描述】:
下面的异常处理方法正确吗?我发现很难记录错误并最终通过电子邮件发送日志文件。 我在哪里编写代码来记录错误并发送电子邮件?
我遇到的一个主要问题是,当在SomeClass1 中生成异常时,它会被记录两次——第二次来自SomeClass2。创建单个自定义异常类型(示例中为SomeException)并在发生时包装System.Exception 是否是个好主意?
当我们有一连串的 try-catch 相互调用时,我对如何以及何时向最终用户显示错误消息感到困惑。
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();
}
}
【问题讨论】:
标签: c# exception-handling