在我的 Autocad.NET 应用程序中,我想使用 log4net 记录所有未处理的异常。 AutoCAD 本身会显示一个带有详细消息的错误对话框 -> 因此必须有一种方法可以注册到某个事件。
我尝试在应用程序初始化时注册 AppDomain.CurrentDomain.UnhandledException
事件:
AppDomain.CurrentDomain.UnhandledException += (s, e) =>
{
System.Exception exception = (System.Exception)e.ExceptionObject;
log.Error(String.Format("Unhandled Exception: {0}\n{1}", exception.Message, exception.StackTrace));
};
但是这个事件永远不会被触发。
最佳答案
在 ObjectARX 中,有一个名为 acedDisableDefaultARXExceptionHandler 的函数。你可以尝试P/Invoke它。
// EntryPoint may vary across autocad versions
[DllImport("acad.exe", EntryPoint = "?acedDisableDefaultARXExceptionHandler@@YAXH@Z")]
public static extern void acedDisableDefaultARXExceptionHandler(int value);
你也可以试试 System.Windows.Forms.Application.ThreadException: http://through-the-interface.typepad.com/through_the_interface/2008/08/catching-except.html
最简单的方法是将所有代码包装在 try/catch 块中。在 AutoCAD 中,有两种方式来执行代码:
使用命令
为了避免重复代码,声明一个这样的接口(interface):
public interface ICommand
{
void Execute();
}
然后将其用于您的命令:
public class MyCommand : ICommand
{
void Execute()
{
// Do your stuff here
}
}
在定义命令的类中,使用此通用方法执行:
void ExecuteCommand<T>() where T : ICommand
{
try
{
var cmd = Activator.CreateInstance<T>();
cmd.Execute();
}
catch (Exception ex)
{
Log(ex);
}
}
现在您的命令如下所示:
[CommandMethod("MYCMD", CommandFlags.Modal)]
public void MyCommand()
{
ExecuteCommand<MyCommand>();
}
在事件处理程序中
在这种情况下,由于您需要事件参数,只需将您的代码直接包装在 try/catch 中。
关于c# - 如何捕获 AutoCAD.NET 中引发的未处理异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12384442/