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?
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.
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.
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.
Calling Stop results in a "Service successfully stopped" message in the Application log.
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;
}
}
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