C# (not ASP/MVC/WinForms) - Catch all exceptions in a class

后端 未结 3 1408
隐瞒了意图╮
隐瞒了意图╮ 2021-02-07 03:31

Some background info

I am programming in a system that uses a proprietary programming language, with the option of using specially attributed .Net classes in the propri

相关标签:
3条回答
  • 2021-02-07 03:44

    I would take a look at using something like Castle Dynamic Proxy.
    This will allow your class method calls to be intercepted in a generic way, which would give you a central place to put a "catch-all" exception handler. (That said, it's unclear to me how your classes are actually instantiated, which might make this approach problematic)

    0 讨论(0)
  • 2021-02-07 03:54

    In Addition to VMAtm's post you can also set event handler for ThreadExceptions

    0 讨论(0)
  • 2021-02-07 04:03

    As I understood the answer, you need to catch and rethrow unhandled exception, right? You can add handler for the AppDomain.UnhandledException Event:

      AppDomain currentDomain = AppDomain.CurrentDomain;
      currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
    
      static void MyHandler(object sender, UnhandledExceptionEventArgs args)
      {
            Exception e = (Exception) args.ExceptionObject;
            // handle exception here, you can easily package exceptions there.
      }
    

    Update:

    I've discovered another event in AppDomain class, AppDomain.FirstChanceException Event:

    Occurs when an exception is thrown in managed code, before the runtime searches the call stack for an exception handler in the application domain.

    May be this can solve your problem - this event occurs before any code in catch blocks.

    0 讨论(0)
提交回复
热议问题