简体   繁体   English

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

[英]How to catch unhandled exceptions thrown in AutoCAD.NET

In my Autocad.NET app I want to log all unhandled exceptions using log4net. 在我的Autocad.NET应用程序中,我想使用log4net记录所有未处理的异常。 AutoCAD itself shows an error dialog with a detailed message -> so there must be a way to register to a certain event. AutoCAD本身会显示一个带有详细消息的错误对话框 - >因此必须有一种方法可以注册到某个事件。

I tried to register the AppDomain.CurrentDomain.UnhandledException event at app initialization: 我尝试在应用初始化时注册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));
};

But this event is never fired. 但这件事从未被解雇过。

In ObjectARX, there is a function called acedDisableDefaultARXExceptionHandler. 在ObjectARX中,有一个名为acedDisableDefaultARXExceptionHandler的函数。 You can try to P/Invoke it. 您可以尝试P / Invoke它。

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

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

The simplest way to do this is to wrap all your code in a try/catch block. 最简单的方法是将所有代码包装在try / catch块中。 In AutoCAD, there is 2 ways to execute code : 在AutoCAD中,有两种执行代码的方法:

With a command 用命令

To avoid duplicate code, declare an interface like this: 为避免重复代码,请声明如下界面:

public interface ICommand
{
  void Execute();
}

Then use it for your command: 然后将它用于您的命令:

public class MyCommand : ICommand
{
  void Execute()
  {
    // Do your stuff here
  }
}

In the class where your commands are defined, use this generic method to execute : 在定义命令的类中,使用此泛型方法执行:

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

Now your command looks like this: 现在您的命令如下所示:

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

In an event handler 在事件处理程序中

In this case, as you need the event arguments, simply wrap your code in the try/catch directly. 在这种情况下,当您需要事件参数时,只需将代码直接包装在try / catch中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM