Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle exception on service startup

I'm writing a series of Windows services. I want them to fail if errors are thrown during startup (in OnStart() method). I had assumed that merely throwing an error in OnStart() would do this, but I'm finding that instead it "Starts" and presents me with a message stating "The service has started, but is inactive. Is this correct?" (Paraphrase). How do I handle the error so it actually fails to start the service?

like image 386
C. Ross Avatar asked Oct 01 '08 17:10

C. Ross


People also ask

How do you handle exceptions in spring boot Microservices?

Define a class that extends the RuntimeException class. You can define the @ExceptionHandler method to handle the exceptions as shown. This method should be used for writing the Controller Advice class file. Now, use the code given below to throw the exception from the API.

What is UseExceptionHandler?

UseExceptionHandler(IApplicationBuilder) Adds a middleware to the pipeline that will catch exceptions, log them, and re-execute the request in an alternate pipeline. The request will not be re-executed if the response has already started.


1 Answers

If the main thing you want is for the Services window to report that there was an error, from what I've tried (.NET3.5 on Windows 7), the only way to do this is by setting the ExitCode. I recommend setting it to 13816, since this results in the message, "An unknown error has occurred." See the windows error codes.

The sample below accomplishes three things.

  1. Setting ExitCode results in a useful message for the end-user. It doesn't affect the Windows Application log but does include a message in the System log.
  2. Calling Stop results in a "Service successfully stopped" message in the Application log.

  3. throwing the exception results in a useful log entry in the Application log.

protected override void OnStart(string[] args) {
    try {
        // Start your service
    }catch (Exception ex) {
        // Log exception
        this.ExitCode = 13816;
        this.Stop();
        throw;
    }  
}
like image 116
Sean Avatar answered Oct 13 '22 07:10

Sean