以下异常处理方法是否正确?我发现很难记录错误,最后通过电子邮件发送日志文件。 我在哪里编写代码来记录错误并发送电子邮件?
我得到的一个主要问题是,当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);
}
}
}
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();
}
}
答案 0 :(得分:5)
以下异常处理方法是否正确?
没有。有几个问题。这是最重要的两个。
<强> 1。你不应该抓住你无法处理的例外
非常重要。所有仅重新抛出或记录异常的异常块都会使代码混乱,而不会添加任何值。仅捕获最顶层中的所有异常(在webservice,MVC控制器,后台线程等中)以防止应用程序崩溃。 (但是,有时 更好 让应用程序崩溃)。
如果方法可以返回预期值,则处理异常。
<强> 2。始终包含原始例外
当您仅复制原始例外中的部分信息时,您隐藏的信息对于将来能够阻止信息非常重要。
如果你必须抓住/抛出其他你应该这样做:
public class CustomException : Exception
{
public CustomException(string msg, Exception inner) : base(msg, inner){}
}
//并在方法中:
public void DoSomething()
{
try
{
SomeCoolOp();
}
catch (Exception err)
{
throw new CustomException("Tried to allocate some cool stuff", err);
}
}
与您的代码相比的变化:
operation specific
消息,即描述发生异常时我们尝试做的事情(而不是使用原始消息)更多信息
我写了几篇关于异常处理的博文。
您可以先阅读:http://blog.gauffin.org/2010/11/do-not-catch-that-exception/
而不是阅读其余内容:http://blog.gauffin.org/tag/exceptions/
答案 1 :(得分:2)
或许可以考虑使用类似ELMAH之类的东西,就像Log4Net一样,它可以配置为将错误记录到文件,数据库表或电子邮件中。