Windows service exception handling with Raygun

| 2 min. (228 words)

One of our users recently asked about Windows service exception handling with Raygun. We include many examples on using Raygun with web sites, desktop apps and mobile apps but nothing about services so I thought it would make a good post.

First of all, with your Raygun account setup, create a new application. Give it the name of your service. You just need to grab the API key for the new app.

Inside your Windows Service app add the following:

public MyService()
{
  InitializeComponent();

  AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}

void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
  var rg = new RaygunClient("YOUR_API_KEY");
  rg.Send((Exception)e.ExceptionObject);

  // NOTE: e.ExceptionObject will always be a Exception in C# & VB
  //       but technically the CLR can throw things that are not exceptions.
  //       Unless you're outside of C#/VB, you don't have to worry about it.
}

You’ll also want to install the Raygun4net nuget package.

Lastly, because we’re hooking at the current AppDomain, be aware that if your Windows Service is going to be spinning up multiple app domains (not common, but maybe you are), remember you’ll want to hook this event for each app domain created.

I hope that helps!

Create your account

Every Raygun user gets a 14 day trial – no credit card required. You can sign up in a matter of seconds. It couldn’t be easier to be improving your software quality.