Where to place a central error handler for a Windows Forms project

In ASP.NET, I can use Application_Error inside global.asax to handle any errors that were not processed.

Is there a window equivalent?

+4
source share
3 answers

Yes, its AppDomain.UnhandledException

 using System; using System.Security.Permissions; public class Test { [SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlAppDomain)] public static void Example() { AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler); try { throw new Exception("1"); } catch (Exception e) { Console.WriteLine("Catch clause caught : " + e.Message); } throw new Exception("2"); // Output: // Catch clause caught : 1 // MyHandler caught : 2 } static void MyHandler(object sender, UnhandledExceptionEventArgs args) { Exception e = (Exception) args.ExceptionObject; Console.WriteLine("MyHandler caught : " + e.Message); } public static void Main() { Example(); } } 
+2
source
 [STAThread] static void Main() { Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException); Application.Run(new FrmMain()); } private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { MessageBox.Show("Unhandled exception: "+e.Exception.ToString()); } 
+1
source

It depends on the architecture of your application. For example, if you are creating an MVC architecture, then this should be in your controller. If you know the Chain of responsability pattern [GOF] or prefer a large handler for all execution types. Otherwise, you will tell us more about your application.

0
source

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


All Articles