Is there a way to globally handle exceptions for a Windows Service? Something similar to the following in Windows Forms applications:
Application.ThreadException += new ThreadExceptionEventHandler(new ThreadExceptionHandler().ApplicationThreadException);
The Global Exception Handler is a type of workflow designed to determine the project's behavior when encountering an execution error. Only one Global Exception Handler can be set per automation project.
Using Exception Filters Note that exception filter does not catch HttpResponseException exception because HttpResponseException is specifically designed to return the HTTP response. We can use exception filter whenever controller action method throws an unhandled exception that is not an HttpResponseException.
ASP.NET Core Error HandlingAn ExceptionFilterAttribute is used to collect unhandled exceptions. You can register it as a global filter, and it will function as a global exception handler. Another option is to use a custom middleware designed to do nothing but catch unhandled exceptions.
Have you tried
AppDomain.CurrentDomain.UnhandledException
This will fire for unhandled exceptions in the given domain no matter what thread they occur on. If your windows service uses multiple AppDomains you'll need to use this value for every domain but most don't.
Here is some pretty robust code we advise people to use when they're implementing http://exceptioneer.com in their Windows Applications.
namespace YourNamespace { static class Program { [STAThread] static void Main() { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { HandleException(e.Exception); } static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { HandleException((Exception)e.ExceptionObject); } static void HandleException(Exception e) { //Handle your Exception here } } }
Thanks,
Phil.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With