Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do error handling in Windows .NET Services

This feels like a question that has probably been asked before but I couldn't find it so am asking (possibly again).

I'm writing a windows service to do a bit of file monitoring and processing. Its all doing what I want but I am aware that there are several places that my code might throw errors when doing read/writes to the file system or event log. I'm goign to put in some try/catches where I expect there to be errors but I was wanting to do some global error handling to pick up all those unforseen problems. I'm not sure how to do this though.

My first thought was to look for some kind of global error handler similar to what I find in ASP.NET projects but couldn't see anything along these lines.

The other thought was that I could just get all my top level function calls and put a try/catch around them. As I see it that would mean putting a try/catch around all my event handler code and my service Start and Stop methods. This doesn't feel like a good way of doing it so I'm thinking I'm probably approaching this in the wrong way. Can anybody suggest what I should be doing in terms of error handling?

I assume that in a service I don't want it to just throw errors because it will potentially stop the service or should I in fact be letting the service collapse and automatically restarting it through teh recovery mechanism I've seen mentioned?

I'm very uncertain here so please share your wisdom with me... :)

like image 856
Chris Avatar asked Dec 06 '25 07:12

Chris


1 Answers

There is no problem in putting a try/catch in the main method of the service and log the errors so you can fix them. If the error caught is unexpected then you may close the service cleanly.

Also, besides the main try/catch, you will have to add a try/catch for every potential exceptions that you cannot avoid to happen (i.e. network issues) so you can act accordingly in order to restore the correct behavior of the application, avoiding the service to crash.

Finally, keep in mind that you will have to do this for every top-method of every distinct thread you have, because the exceptions are not propagated outside the scope of a thread.

like image 141
David Espart Avatar answered Dec 07 '25 21:12

David Espart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!