如何捕获 AutoCAD.NET 中引发的未处理的异常

mam*_*ack 5 c# autocad autocad-plugin

在我的 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));
};
Run Code Online (Sandbox Code Playgroud)

但此事件从未被触发。

Max*_*nce 4

在ObjectARX中,有一个名为acedDisableDefaultARXExceptionHandler的函数。您可以尝试 P/Invoke 它。

    // EntryPoint may vary across autocad versions
    [DllImport("acad.exe", EntryPoint = "?acedDisableDefaultARXExceptionHandler@@YAXH@Z")]
    public static extern void acedDisableDefaultARXExceptionHandler(int value);
Run Code Online (Sandbox Code Playgroud)

您还可以尝试 System.Windows.Forms.Application.ThreadException:http://through-the-interface.typepad.com/through_the_interface/2008/08/writing- except.html

最简单的方法是将所有代码包装在 try/catch 块中。在 AutoCAD 中,有两种执行代码的方法:

用命令

为了避免重复代码,请声明如下接口:

public interface ICommand
{
  void Execute();
}
Run Code Online (Sandbox Code Playgroud)

然后将其用于您的命令:

public class MyCommand : ICommand
{
  void Execute()
  {
    // Do your stuff here
  }
}
Run Code Online (Sandbox Code Playgroud)

在定义命令的类中,使用此通用方法来执行:

void ExecuteCommand<T>() where T : ICommand
{
  try
  {
    var cmd = Activator.CreateInstance<T>();
    cmd.Execute();
  }
  catch (Exception ex)
  {
    Log(ex);
  }
}
Run Code Online (Sandbox Code Playgroud)

现在你的命令看起来像这样:

[CommandMethod("MYCMD", CommandFlags.Modal)]
public void MyCommand()
{
  ExecuteCommand<MyCommand>();
}
Run Code Online (Sandbox Code Playgroud)

在事件处理程序中

在这种情况下,当您需要事件参数时,只需将代码直接包装在 try/catch 中即可。