0

Generic error while starting the service

While starting the installed service through service.msc, if the start up fails then windows shows a generic message in the pop up. But, in certain cases, we want to propagate a meaningful message here explaining why the service did not start, for example, if the customers fail to configure few things during installation.

Is there any way in C# through which we can achieve this functionality?

theimpatientcoder
  • 1,184
  • 3
  • 19
  • 32
  • 1
    I hope this may help https://stackoverflow.com/questions/2456819/how-can-i-set-up-net-unhandledexception-handling-in-a-windows-service setting up https://stackoverflow.com/questions/158772/handle-exception-on-service-startup?rq=1 – Gaurav Chaudhary Dec 26 '22 at 14:46
  • I don't think a custom message is possible. You should explore Gaurav's link... basically you will need to look into the event log or dump the error somewhere you can read it. – Kit Dec 27 '22 at 15:03
  • are you starting the service manually from service.msc or from c# code ? – Ben.S Dec 28 '22 at 01:03
  • 2
    Catch the exception and set an `ExitCode` (https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicebase.exitcode) to a value that Windows already knows (and rethrow), for example 1610 will display a nice *"The configuration data for this product is corrupt. Contact your support personnel."* message. https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--1300-1699- and also you can add information to the Event Log using `ServiceBase.EventLog` https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicebase.eventlog – Simon Mourier Dec 29 '22 at 11:00

1 Answers1

-1

Try this method to display a custom message on starting failure

protected override void OnStart(string[] args){
try
{
    // Perform startup tasks here
}
catch (Exception ex)
{
    // Display a custom message in the event of an error
    throw new Exception("Service failed to start. Error: " + ex.Message);
}}

Similarly, you can use OnContinue, OnPause, and OnStop.

Apocryphon
  • 35
  • 2
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 01 '23 at 17:48
  • 1
    If an exception is thrown and doesn't show its message, how would throwing another exception make a difference? Please explain. – Gert Arnold Jan 01 '23 at 19:07
  • This does not work. The exception message is not available on UI – theimpatientcoder Jan 02 '23 at 11:15