How to catch unhandled exceptions thrown in AutoCAD.NET

In my Autocad.NET application, I want to log all unhandled exceptions using log4net. AutoCAD itself displays a dialog box with a detailed message →, so there should be a way to register for a specific event.

I tried to register the AppDomain.CurrentDomain.UnhandledException event when initializing the application:

 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 never fires.

+4
source share
1 answer

In ObjectARX, there is acedDisableDefaultARXExceptionHandler function. You can try P / Invoke it.

  // 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

The easiest way to do this is to wrap all your code in a try / catch block. There are two ways to execute code in AutoCAD:

Using command

To avoid code duplication, declare the interface as follows:

 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 general 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 the event handler

In this case, since you need the event arguments, just wrap your code directly in try / catch.

+4
source

Source: https://habr.com/ru/post/1433741/


All Articles