c# - 如何捕获 AutoCAD.NET 中抛出的未处理异常

标签 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));
};

但是这个事件永远不会被触发。

最佳答案

在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 block 中。在 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/

相关文章:

c# - C# 旋转函数的奇怪行为

c# - 在 AutoCAD 中以一定角度插入 block (C#)

c# - 如何将用户输入数据从控制台程序获取到C#程序?

c# - 当我在组合框中选择一种语言时,如何更改所有表单的文本?

lisp - 如何使用 AutoLISP 插入具有自定义属性的 block ?

c++ - 在 C++ 中链接和通信到 AutoCAD

c# - 文件读取外来字符

c# - 通过 Javascript 验证消息

layout - Autocad - 自动更新 lisp 生成的字段(布局计数器)

c# - 在 AutoCAD 中限制另一个形状内的形状移动