【问题标题】:How to catch unhandled exceptions thrown in AutoCAD.NET如何捕获 AutoCAD.NET 中引发的未处理异常
【发布时间】:2012-09-05 06:04:22
【问题描述】:

在我的 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));
};

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

【问题讨论】:

  • 也许这个异常是由对话框处理的。
  • 如果 AutoCAD 没有崩溃 - 这意味着异常已由 AutoCAD 处理
  • 在AutoCAD的异常处理之前有办法处理吗?
  • 在另一个 AppDomain 中运行您的代码。
  • @HansPassant 任何提示如何在 AutoCAD 扩展应用程序中做到这一点?

标签: c# autocad autocad-plugin


【解决方案1】:

在 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 中,有两种执行代码的方法:

用命令

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

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 中即可。

【讨论】:

  • 您的链接描述了我同时找到的最佳方法。谢谢
  • 调用 acedDisableDefaultARXExceptionHandler 来禁用对我没有任何改变
猜你喜欢
  • 2017-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
  • 2014-03-19
  • 2015-09-10
  • 2011-10-27
相关资源
最近更新 更多