Michael Levy
Michael Levy

Reputation: 13287

How to map a thrown exception to an event ID for logging?

In our code base, an error condition may cause an exception to be thrown. Somewhere else in the code an exception handler catches the exception and logs the error to the Windows Event log.

When the error is detected and the exception is thrown is where we have the most information about the error condition and I'd like to identify the error with a unique event ID that will be logged in the windows event log.

What is the best way to include this event ID in the exception that is thrown?

I thought about using Exception.HResult, but that seems intended to be used for COM/win32 interop. Do people use HResult for this purpose? It seems one could map severity to the loglevel, the facility code to the Event source, and the Hresult code to an Event ID. Is this a common approach?

I thought about using the Exception.Data dictionary and adding a named "EventID" value to the thrown exception so my handler can use that value to log the EventID.

Anyone have any good advice or suggestions?

Upvotes: 5

Views: 1872

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156459

The approaches you've mentioned are certainly valid. Another approach that I've used in similar situations is to make my exception type implement a particular interface with a method or property that provides the event ID.

In all of these approaches, the key is to never eat exceptions, but to wrap them in other exceptions with more data where appropriate, and then at the top level walk through the InnerException chain until you find the exception you're looking for. The advantage of using a specific interface is that it's easy to identify the exception classes that are providing the information in the way you want it, whereas any exception can have an HResult or a value in Exception.Data.

Upvotes: 3

Related Questions