我有一个类库,我正在使用控制台应用程序进行调试。这非常有效。
该类旨在与服务器上的现有Windows服务一起使用。我没有很多访问服务器的权限。
我更新服务以使用类库。它包含在解决方案的类库中,它被引用,并且它包含在页面中。
但是,当它在服务器上构建时,它会返回一个null对象。
相关服务:
using MyNamespace;
...
private void TimerTick(){
//this is called every minute
EventLog.WriteEntry("myLog", "Start test", EventLogEntryType.Information);
try
{
EventLog.WriteEntry("myLog", "I see this", EventLogEntryType.Information);
MyClass test1 = new MyClass(); //Error occurs here
EventLog.WriteEntry("myLog", "I never see this", EventLogEntryType.Information);
test1.MyFunction();
}
catch (Exception e)
{
EventLog.WriteEntry("myLog", e.Message, EventLogEntryType.Information);
}
EventLog.WriteEntry("myLog", "Conclude test", EventLogEntryType.Information);
}
相关课程:
namespace MyNamespace
{
public class MyClass
{
public SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString);
public void MyFunction(){
EventLog.WriteEntry("MyLog", "Get links", EventLogEntryType.Information);
}
}
}
在事件日志中,我得到了标准:
对象引用未设置为对象的实例。
服务器上的构建和部署没有错误。该服务按预期运行,它只是尝试实例化类时的空引用异常。
我对C#/ .net
相当新当我获得的唯一错误消息是通过EventLog时,是否有更好的方法来解决此问题?
类实例化抛出空引用异常的可能原因是什么?
我尝试过的事情
首先,使用Exception.ToString()
来获取堆栈跟踪,而不是像我最初那样使用Exception.Message
。这给了我很多调试信息。
其次,查看类构造函数本身的错误,因为类实例化不能抛出空引用本身。
答案 0 :(得分:0)
Exception.Message
返回有限的信息。记录错误时,可以使用Exception.ToString()
记录更好的调试信息:
try
{
//your code
}
catch (Exception e)
{
EventLog.WriteEntry("myLog", e.ToString(), EventLogEntryType.Information);
}
类实例化也不可能抛出空引用异常 - 如果在实例化过程中看到一个,则类中的某些内容必须抛出错误。使用Exception.ToString()
应该提供必要的信息来识别具体问题。