Global error handler for class library in C #

Is there a way to catch and handle an exception for all exceptions thrown in any of the class library methods?

I can use the try catch construct inside each method, as in the code example below, but I was looking for a global error handler for the class library. The library can be used by ASP.Net or Winforms applications or another class library.

The advantage will be easier to develop, and you do not need to do the same thing many times in each method.

public void RegisterEmployee(int employeeId) { try { .... } catch(Exception ex) { ABC.Logger.Log(ex); throw; } } 
+4
source share
1 answer

You can subscribe to a global event handler, such as AppDomain.UnhandledException , and check the method that throws the exception:

 AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException; private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs) { var exceptionObject = unhandledExceptionEventArgs.ExceptionObject as Exception; if (exceptionObject == null) return; var assembly = exceptionObject.TargetSite.DeclaringType.Assembly; if (assembly == //your code) { //Do something } } 
+4
source

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


All Articles